开发者

Rails: How to find records by associations within a new array?

I have created a has_many relationship where a Food can be served at several different kinds of meals. For instance, eggs can be served at a user's breakfast or brunch.

That is, a Food is allowed to be served only at certain meals and this is tracked with a has_many relationship named meal_type.

Now suppose I have 开发者_Go百科filtered my initial table by a certain query, such as:

@hot_foods = Foods.where(:is_hot => 1). 

And now I want to find out of the hot foods, only those that can be served at lunch.

Specifically, the relationships are given as follows:

class Food
has_many :meals, :through => :relationships
has_many :relationships

class Meal
has_many :foods, :through => :relationships
has_many :relationships

class Relationships
belongs_to :food
belongs_to :meals 

How would I perform this query?


To make the query easier, start with the Meal and work backwards:

@meal = Meal.find_by_name('Lunch')
@meal.foods.where('foods.is_hot' => true)

Having properly defined has_many ..., :through relationships allows you do to this in a pretty straight-forward way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜