Rails - 使用 group_by 和 has_many :through 并尝试访问连接表属性
有关一些背景信息,请参阅我的问题:使用STI的Rails应用程序——提取这些记录的最简单方法?
我有一些模型通过使用第三个连接表的关系与has_many连接(配方和通过 RecItem 加入成分)。
所以上一个问题的人帮助我按类型对我的食谱成分进行分组 - 这正是我想要的。然而,现在我正在访问@recipe.ingredients而不是@recipe.rec_items,我无法返回rec_items连接表中存储的数据(例如成分的数量,烹饪多长时间等...... )
在使用group_by之前,我像这样迭代每个食谱的rec_items:
<% @recipe.rec_items.each do |rec_item| %>
<%= rec_item.ingredient.name %><br />
<%= rec_item.amount %><br />
<% end -%>
现在我正在对@recipe.ingredients进行分组,我怎样才能回到rec_items与这个食谱有关? (如果我执行成分.rec_items,它会为我提供所有食谱的rec_items...同样,我可以使用笨重的语句来做到这一点,例如:
ingredient.rec_items.find_by_recipe_id(@recipe.id).amount
但这似乎是错误的...)有没有一种简单的方法来实现这些目标? (获取特定食谱的成分列表,按:类型排序/分组,同时仍然能够访问每个食谱/成分配对的rec_items中的附加信息?)
谢谢!
For some background, please see my question: Rails app using STI -- easiest way to pull these records?
I have some models joined with a has_many through relationship using a third join table (Recipe and Ingredient joined through RecItem).
So the guys on the prior question helped me to group my recipe's ingredients by type - this is exactly what I wanted. However, now that I am accessing @recipe.ingredients instead of @recipe.rec_items, I can't get back to the data stored in the rec_items join table (stuff like amount of ingredient, how long to cook it, etc...)
Prior to using the group_by, I was iterating through each recipe's rec_items like so:
<% @recipe.rec_items.each do |rec_item| %>
<%= rec_item.ingredient.name %><br />
<%= rec_item.amount %><br />
<% end -%>
Now that I am grouping @recipe.ingredients, how can I follow back to the rec_items related to this recipe? (If I do ingredient.rec_items it gives me rec_items for all recipes...again, I can do this with clunky statements like:
ingredient.rec_items.find_by_recipe_id(@recipe.id).amount
but that seems wrong...) Is there an easy way to accomplish these goals? (getting a list of a particular recipe's ingredients, sorted/grouped by :type, while still being able to access the additional info in rec_items for each recipe/ingredient pairing?)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
再次发布相同的答案,稍加修改:
您可以使用
group_by在这里。顺便说一下,你最好在配方查询中使用
includes
,否则会有很多查询。Posting same answer again, with a little modification:
You can use
group_by
here. By the way you better useincludes
in the query for recipe, otherwise there are going to be many queries.