【问题标题】:How to access two polymorphic associations with one query?如何通过一个查询访问两个多态关联?
【发布时间】:2020-08-17 08:27:58
【问题描述】:

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

怎么做?

【问题讨论】:

  • has_many :people, -&gt; { joins(:carriers, :clients) }"' 适合你吗?
  • 不,@benjessop,不幸的是它没有。我收到此错误:ActiveRecord::ConfigurationError (Can't join 'Person' to association named 'carriers'; perhaps you misspelled it?)

标签: ruby-on-rails ruby activerecord


【解决方案1】:

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

【讨论】:

  • 谢谢。但是如何过滤关联?我尝试了类似Account.includes(:carrier_people, :client_people).people.where(:first_name =&gt; "John") 的东西,但它给了我一个错误:NoMethodError (undefined method 'people' for #&lt;Account::ActiveRecord_Relation:0x00007fe4e46f71d0&gt;)
  • 您可以这样做,Account.includes(:carrier_people, :client_people).where(carrier_people: {first_name: "John"}).or(Account.includes(:carrier_people, :client_people)。 where(client_people: {first_name: "John"}))
  • 哇,比我想象的要复杂!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多