通过关系迭代 has_many 并包含来自加入 table 的数据

Iterate over has_many through relationship and include data from joining table

我有一个非常简单的 rails 应用程序,它包含三个模型:食谱、成分和连接 table 数量,用于存储食谱中每种成分的数量。对于一个食谱,我想列出所有相关成分和加入 table 中发现的数量。我如何遍历成分,但也包括来自数量的数据 table?

class Recipe < ActiveRecord::Base

    has_many :quantities
    has_many :ingredients, through: :quantities
    accepts_nested_attributes_for :quantities, :reject_if => :all_blank, :allow_destroy => true
end

和:

class Ingredient < ActiveRecord::Base

    has_many :quantities
    has_many :recipes, through: :quantities
end

终于加入 table:

class Quantity < ActiveRecord::Base
    belongs_to :recipe
    belongs_to :ingredient
    accepts_nested_attributes_for :ingredient, allow_destroy: true
end

看起来应该很容易进行此迭代,但我不确定如何进行。

show.html.erb:

<% @recipe.ingredients.each do |ingredient| %>
    <% #I know the line below is wrong, but not sure how
    # to iterate over the ingredients for the recipe and
    # include the amount field from the quantities table
    # as well as the ingredient name. %>
    <li><%= ingredient.amount ingredient.name  %></li>
<% end %>

谢谢!

在控制器的操作中执行如下操作:

@recipe = Recipe.includes(:ingredients, :quantities).find(params[:id]) # avoid N+1

然后,在您看来:

<% @recipe.quantities.each do |quantity| %>
  <%= quantity.ingredient.name %> - 
  <%= quantity.amount %>
<% end %>

联接 table quantities 可能只有一行用于 recipeingredient 的组合,即使 has_many :through 实现允许对于多行。

这允许按如下方式访问成分数量和名称:

<% @recipe.ingredients.each do |ingredient| %>
  <li>
    <%= ingredient.quantities.first.amount %>
    <%= ingredient.name  %>
  </li>
<% end %>