Ruby on rails 迭代具有多个贯穿关系,并包含来自联接表的数据
我有一个非常简单的rails应用程序,它有三个模型:配方、配料和一个连接表,用于存储配方中每种配料的数量。对于一个配方,我想列出所有相关成分和加入表中的数量。我如何迭代成分,但也包括数量表中的数据Ruby on rails 迭代具有多个贯穿关系,并包含来自联接表的数据,ruby-on-rails,join,iteration,has-many-through,Ruby On Rails,Join,Iteration,Has Many Through,我有一个非常简单的rails应用程序,它有三个模型:配方、配料和一个连接表,用于存储配方中每种配料的数量。对于一个配方,我想列出所有相关成分和加入表中的数量。我如何迭代成分,但也包括数量表中的数据 class Recipe < ActiveRecord::Base has_many :quantities has_many :ingredients, through: :quantities accepts_nested_attributes_for :quant
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
类配方:all\u blank、:allow\u destroy=>true
终止
以及:
class成分
最后连接表:
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 %>
-
对于配方
和成分
的组合,联接表数量
可能只有一行,即使有许多:通过实现允许多行
这允许访问成分数量和名称,如下所示:
<% @recipe.ingredients.each do |ingredient| %>
<li>
<%= ingredient.quantities.first.amount %>
<%= ingredient.name %>
</li>
<% end %>
<% @recipe.ingredients.each do |ingredient| %>
<li>
<%= ingredient.quantities.first.amount %>
<%= ingredient.name %>
</li>
<% end %>