ruby on rails - Iterate over has_many through relationship and include data from joining table -
i have simple rails app 3 models: recipes, ingredients, , joining table quantities stores amount of each ingredient in recipe. 1 recipe, want list associate ingredients , amount found in joining table. how iterate on ingredients, include data quantities 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
and:
class ingredient < activerecord::base has_many :quantities has_many :recipes, through: :quantities end
and joining table:
class quantity < activerecord::base belongs_to :recipe belongs_to :ingredient accepts_nested_attributes_for :ingredient, allow_destroy: true end
it seems should easy iteration not sure how.
show.html.erb:
<% @recipe.ingredients.each |ingredient| %> <% #i know line below wrong, not sure how # iterate on ingredients recipe , # include amount field quantities table # ingredient name. %> <li><%= ingredient.amount ingredient.name %></li> <% end %>
thank you!
in controller's action this:
@recipe = recipe.includes(:ingredients, :quantities).find(params[:id]) # avoid n+1
and then, in view:
<% @recipe.quantities.each |quantity| %> <%= quantity.ingredient.name %> - <%= quantity.amount %> <% end %>
Comments
Post a Comment