Undistraction
Undistraction

Reputation: 43401

Filtering Association Based On Through Model Attribute

I have a model:

class Example < ActiveRecord

   has_many :bars
   has_many :foo, through: :bars

end

Each instance of Bar has an attribute called value which can be either 1,2,3 or 4.

How can I query an instance of Example to return all its Foo associations where the linking Bar model has a value of 3?

Upvotes: 0

Views: 51

Answers (1)

Tumas
Tumas

Reputation: 1727

Since it will fetch foos by joining with bars anyway, something like this should work:

example.foos.where("bars.value = ?", 3)

Upvotes: 1

Related Questions