如何用一个查询访问两个多态关联



在我的Rails 6应用程序中,我有以下模型:

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

如何在一个查询中访问帐户的carriersclients

我很想做一些类似account.people的事情,向所有帐户的人员展示,但还没有找到实现这一点的方法。

如何做到这一点?

您不能对两个关联使用相同的方法名,而是可以将其重命名为carrier_peopleclient_people,并渴望加载这两个关联。

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

你可以像这样急切地加载。

Account.includes(:carrier_people, :client_people)

最新更新