ruby-on-rails - 如何通过一个查询访问两个多态关联?
问题描述
在我的 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
andclient_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)
推荐阅读
- javascript - svelte + rollup 中的环境变量
- php - ACF 未在 wp 主题的页脚中显示值
- vue.js - 如何从另一个数据属性访问 Vuejs 数据属性?
- bash - 命令在 docker 中手动成功,但不是通过 bash 脚本
- java - 在运行时将信息保存在 JAR 旁边
- amazon-web-services - 使用 AWS KMS 进行 PGP 解密?
- spring - Spring 异常处理程序 - 处理多个异常
- javascript - 脚本 google sheet 表单自动完成和填充单元格
- html - Outlook 2019 上的额外空间。右侧和左侧
- kotlin - 一个以单个 lambda 表达式为主体的 Kotlin 函数