Rails:如何通过新数组中的关联查找记录?

发布于 2024-11-04 06:18:50 字数 562 浏览 2 评论 0原文

我创建了一个 has_many 关系,其中一种食物可以在几种不同类型的膳食中提供。 例如,可以在用户的​​早餐或早午餐中提供鸡蛋。

也就是说,仅允许在某些膳食中提供食物,并且通过名为 Meal_type 的 has_many 关系来跟踪这一点。

现在假设我已经通过某个查询过滤了我的初始表,例如:

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

现在我想找出热食,只找出那些可以在午餐时提供的食物。

具体来说,关系如下:

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 

我将如何执行此查询?

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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十雾 2024-11-11 06:18:50

为了使查询更容易,从 Meal 开始并向后工作:

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

正确定义 has_many ..., :through 关系允许您以非常直接的方式执行此操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文