How to access two polymorphic associations with one query?

Viewed 70

In my Rails 6 app I have these models:

class Account < ApplicationRecord

  has_many :carriers
  has_many :clients

  # Unfortunately, these two don't work together. I have to uncomment one of them to get the other one to work:
  has_many :people, :through => :carriers # works but omits clients
  has_many :people, :through => :clients # works but omits carriers

end

class Carrier < ApplicationRecord

  belongs_to :account

  has_many :people, :as => :personalizable

end

class Client < ApplicationRecord
  
  belongs_to :account

  has_many :people, :as => :personalizable

end

class Person < ApplicationRecord

  belongs_to :personalizable, :polymorphic => true

end

How can I access an account's carriers and clients in one query?

I would love to do something like account.people to show all the account's people but haven't found a way to achieve that yet.

How can it be done?

1 Answers

You cannot use same method name for two associations instead you can rename it as carrier_people and client_people and eager load both.

class Account < ApplicationRecord

  has_many :carriers
  has_many :clients

  has_many :carrier_people, :through => :carriers, source: :people # works but omits clients
  has_many :client_people, :through => :clients, source: :people # works but omits carriers

end

You can eager load like this.

Account.includes(:carrier_people, :client_people)
Related