0

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?

Suganya Selvarajan
  • 962
  • 1
  • 11
  • 33
  • The `account_id=` is becuase of the `has_many`. You could potentially just replace this with a `scope`. e.g. `scope :all_connections, ->(account) {account.connections.or(Connection.where(account_id: account.ancestry.select(:id))}`. Please note that this will only run 1 depth though if you want the full ancestry chain you have to write something a bit more complex (recursive CTE) or use a gem that provides this functionality(e.g. `ancestry`) – engineersmnky May 13 '21 at 13:11
  • Can you please show how the associations between your 2 models are defined? – Joel Blum May 13 '21 at 13:24
  • Not explicit duplicate of https://stackoverflow.com/questions/24642005/rails-association-with-multiple-foreign-keys, but answers there could help you understand your issue – mikdiet May 13 '21 at 13:33

0 Answers0