gpt4 book ai didi

ruby-on-rails - 如何通过一个查询访问两个多态关联?

转载 作者:行者123 更新时间:2023-12-04 09:06:01 24 4
gpt4 key购买 nike

在我的 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_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)

关于ruby-on-rails - 如何通过一个查询访问两个多态关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63447222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com