[英]Rails how to access child model attributes in where
Let's say I have two models: 假设我有两个模型:
Campaign and Qualification. 活动和资格。 Campaign
has_one :qualification
and Qualification belongs_to :campaign
. 广告系列
has_one :qualification
和Qualification belongs_to :campaign
。
Let's say that Qualification has a male_gender
boolean attribute, what's the most effective way to find all campaigns that have a qualification with male_gender
== true
假设Qualification具有
male_gender
布尔值属性,查找所有具有male_gender
== true
资格的广告系列的最有效方法是
One way would be to loop through qualification with male_gender
indexed. 一种方法是遍历具有
male_gender
索引的资格。 Create an array of campaign_ids, and then get campaigns with those ids, but this seems not very effective. 创建一个campaign_ids数组,然后使用这些ID获得广告系列,但这似乎不是很有效。
Ideally I'd like to do something like Campaign.where("qualification.male_gender: true")
理想情况下,我想做类似
Campaign.where("qualification.male_gender: true")
Is that possible? 那可能吗? Is there a better way to do this?
有一个更好的方法吗?
You certainly can do this. 您当然可以做到。 Using a join you can reference the other table in your where query:
使用联接,您可以在where查询中引用另一个表:
Campaign.joins(:qualification).where(qualifications: {male_gender: true})
Rich Peck edit Rich Peck编辑
You could also put this into a scope : 您也可以将其放入范围内 :
#app/models/campaign.rb
class Campaign < ActiveRecord::Base
scope :male_gender, -> { joins(:qualification).where(qualifications: {male_gender: true}) }
end
... which would allow you to call @campaigns = Campaign.male_gender
...这将允许您调用
@campaigns = Campaign.male_gender
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.