首页 > 解决方案 > 如何通过一个查询访问两个多态关联?

问题描述

在我的 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所有帐户的人展示,但还没有找到实现这一目标的方法。

怎么做到呢?

标签: ruby-on-railsrubyactiverecord

解决方案


您不能对两个关联使用相同的方法名称,而是可以将其重命名为carrier_peopleandclient_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)

推荐阅读