Rails - using group_by and has_many :through and trying to access join table attributes

血红的双手。 提交于 2020-01-17 02:23:02

问题


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!


回答1:


Posting same answer again, with a little modification:

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


来源:https://stackoverflow.com/questions/7195924/rails-using-group-by-and-has-many-through-and-trying-to-access-join-table-att

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!