Rails-使用group_by和has_many:through并尝试访问联接表属性 [英] Rails - using group_by and has_many :through and trying to access join table attributes

查看:76
本文介绍了Rails-使用group_by和has_many:through并尝试访问联接表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些背景,请参阅我的问题:

For some background, please see my question: Rails app using STI -- easiest way to pull these records?

我有一些模型通过使用第三个联接表(通过RecItem联接的配方和成分)通过关系与has_many联接.

I have some models joined with a has_many through relationship using a third join table (Recipe and Ingredient joined through RecItem).

因此,上一个问题的人帮助我按类型对食谱的成分进行分组-这正是我想要的.但是,现在我正在访问@ recipe.ingredients而不是@ recipe.rec_items,我无法返回存储在rec_items联接表中的数据(诸如配料的数量,煮多长时间等). )

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...)

在使用group_by之前,我像这样反复遍历每个食谱的rec_items:

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

现在我要对@ recipe.ingredients进行分组,我如何才能回到与该食谱相关的rec_items? (如果我做Ingredient.rec_items,它将为我提供所有食谱的rec_items……再次,我可以使用笨拙的语句来做到这一点,例如:

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

但这似乎是错误的...)有没有简单的方法可以实现这些目标? (获取特定配方成分的列表,按:type进行排序/分组,同时仍然能够访问rec_items中每个配方/成分配对的其他信息?)

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

谢谢!

推荐答案

再次修改后再次发布相同的答案:

Posting same answer again, with a little modification:

您可以在此处使用 group_by .顺便说一下,您最好在配方查询中使用includes,否则将会有很多查询.

You can use group_by here. By the way you better use includes in the query for recipe, otherwise there are going to be many queries.

recipe.rec_items.group_by {|ri| ri.ingredient.type}.each do |type, rec_items|
  puts type

  rec_items.each do |rec_item|
    puts rec_item.inspect
    puts rec_item.ingredient.inspect
  end
end

这篇关于Rails-使用group_by和has_many:through并尝试访问联接表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆