re5et
re5et

Reputation: 4275

Referencing a belonged_to items owner in Rails / ActiveRecord query

Lets say I have a Person model and a Opinion model. Opinions belong to Person, a Person has many Opinions. Some people are shy.

I am trying to find a set of opinions where the person is 'not shy' or something along those lines. Is there a way to do this that does not involve finding all people who are not shy and then finding those people's opinions? I would like to do something like the pseudo-code below:

@opinions = Opinion.all.where_owner_person('shy = false')

this might be something obvious I have missed, but I can't seem to come up with the right phrasing in my searches to catch the answer.

thanks in advance.

Upvotes: 1

Views: 105

Answers (1)

Matt
Matt

Reputation: 5398

This should work:

@opinions = Opinion.joins(:person).where(:people => { :shy => false })

ActiveRecord documentation has some more examples.

Upvotes: 2

Related Questions