如何解决如何通过一个查询访问两个多态关联?
在我的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
如何通过一个查询访问帐户的carriers
和 clients
?
我想做类似account.people
的事情来向所有展示该帐户的人员,但还没有找到实现此目标的方法。
怎么办?
解决方法
您不能对两个关联使用相同的方法名称,而是可以将其重命名为carrier_people
和client_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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。