Rails:如何通过新数组中的关联查找记录?
我创建了一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了使查询更容易,从 Meal 开始并向后工作:
正确定义
has_many ..., :through
关系允许您以非常直接的方式执行此操作。To make the query easier, start with the Meal and work backwards:
Having properly defined
has_many ..., :through
relationships allows you do to this in a pretty straight-forward way.