Rails 4 - 在视图中访问连接表值 [英] Rails 4 - Access Join Table Value in views
问题描述
我有以下型号
类配方
我已经通过 rails 控制台检查过这个 has_many 通过多对多关系运作良好.
连接表 RecipeIngredient 有一个属性,在模式中是:
t.text "金额"
我想显示来自 Ingredient 的名称以及来自 RecipeIngredient 的与 Recipe 关联的数量.
我在 RecipeController 的 show action 中包含了以下几行:
def 显示@recipe = Recipe.includes(:ingredients).find(params[:id])结尾
这里是 recipes/show.html.erb:
<% title @recipe.name %><div class="col-md-12"><div class="group"><%= link_to("Edit", edit_recipe_path(@recipe), class: "btn btn-primary pull-right")%>
<h2><%=@recipe.name %></h2><p><%=@recipe.description%></p><ul>成分:<% @recipe.ingredients.each 做 |i|ri = i.recipe_ingredients.where("recipe_id: ?", @recipe.id) %><li><%=link_to(i.name,成分路径(i))%></li><p><%=ri.amount %</p><%结束%>
上面的代码在没有连接表部分的情况下运行良好.但是在引入之后,Recipes#show 中的 NoMethodError 被引发,告诉这是一个未定义的方法.
那么我如何访问该值?
@recipe.ingredients.select('ingredients.*, recipe_ingredients.amount').each do |i|<li><%=link_to(i.name,成分路径(i))%></li><p><%=i.amount %</p>结尾
-- 可能是您可以为该特定属性金额"使用委托
I have the following models
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, through: :recipe_ingredients
end
class Ingredient < ActiveRecord::Base
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
I have checked through rails console that this has_many through many-to-many relation works well.
There is one attribute in the join table RecipeIngredient, in schema it is:
t.text "amount"
I would like to display the name from Ingredient and the amount from RecipeIngredient associated with Recipe.
I have included the following lines in RecipeController's show action:
def show
@recipe = Recipe.includes(:ingredients).find(params[:id])
end
Here's recipes/show.html.erb:
<% title @recipe.name %>
<div class="col-md-12">
<div class="group">
<%= link_to("Edit", edit_recipe_path(@recipe), class: "btn btn-primary pull-right")%>
</div>
<h2><%= @recipe.name %></h2>
<p><%= @recipe.description %></p>
<ul>Ingredients:
<% @recipe.ingredients.each do |i| ri = i.recipe_ingredients.where("recipe_id: ?", @recipe.id) %>
<li><%= link_to(i.name, ingredient_path(i)) %></li>
<p><%= ri.amount %></p>
<% end %>
</div>
The above code works well without the join table part. But after it was introduced, an NoMethodError in Recipes#show is raised, telling this is an undefined method.
How can I access the value then?
@recipe.ingredients.select('ingredients.*, recipe_ingredients.amount').each do |i|
<li><%= link_to(i.name, ingredient_path(i)) %></li>
<p><%= i.amount %></p>
end
-- may be u can use delegates for that particular attribute "amount"
这篇关于Rails 4 - 在视图中访问连接表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!