Home Ask Login Register

Developers Planet

Your answer is one click away!

Tom Hammond February 2016

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.

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?

Answers


Jon February 2016

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

Post Status

Asked in February 2016
Viewed 1,301 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life