I have a Account table. which has self association using ancestry gem. Account has ancestry column using which we can get the parent account.
Account
has_many :connections
Also, I have connections table. which
belongs_to :account
Now the set up I have has a parent account
id: 1, name: 'Parent', ancestry: NULL
child account:
id: 2, name: 'Child', ancestry: 1
and a connection:
id: 1, name: 'child-connection', account_id: 2
so I am able to get all connections of as account using
account.connections
I am trying to define a runtime has_many association specific to a class like this
Account.send(:has_many, :all_connections, ->(account) {Connection.where('account_id IN (?) OR account_id IN (?)', account.id, account.ancestry) }, class_name: Connection.name)
But doing account.all_connections always run,
SELECT `connections`.* FROM `connections` WHERE `connections`.`discarded_at` IS NULL AND `connections`.`account_id` = 447549 AND (account_id IN (447549) OR account_id IN (NULL))
Not sure why AND connections
.account_id
= 447549 is getting appended.
Is there an alternate way to achieve this?