Reputation: 6080
Let's say I have two models:
Campaign and Qualification. Campaign has_one :qualification
and 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
One way would be to loop through qualification with male_gender
indexed. Create an array of campaign_ids, and then get campaigns with those ids, but this seems not very effective.
Ideally I'd like to do something like Campaign.where("qualification.male_gender: true")
Is that possible? Is there a better way to do this?
Upvotes: 1
Views: 1071
Reputation: 10898
You certainly can do this. Using a join you can reference the other table in your where query:
Campaign.joins(:qualification).where(qualifications: {male_gender: true})
Rich Peck edit
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
Upvotes: 4