我在这里有两个模型,其中Item和RecipeIngredient如下所示,其中RecipeIngredient属于Item。
class Item < ApplicationRecord
belongs_to :item_type, :class_name=>ItemType, :foreign_key=>"item_type_id"
end
class RecipeIngredient < ApplicationRecord
belongs_to :item, :class_name=>Item, :foreign_key=>"item_id"
belongs_to :ingredient, :class_name=>Ingredient, :foreign_key=>"ingredient_id"
validates_numericality_of :quantity
end
我有项目的索引页面,我已经为RecipeIngredients创建了索引页面的链接,我将URL中的项目ID作为参数传递。
<p id="notice"><%= notice %></p>
<h1>Items</h1>
<table>
<thead>
<tr>
<th>Item</th>
<th>Item type</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @items.each do |item| %>
<tr>
<td><%= item.item %></td>
<td><%= item.item_type.item_type %></td>
<td><%= link_to 'Show', item %></td>
<td><%= link_to 'Edit', edit_item_path(item) %></td>
<td><%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Add Recipe', recipe_ingredients_path(:item_id =>item.id) %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Item', new_item_path %>
<%= link_to "Home", '/' %>
我有RecipeIngredients的控制器如下。
def index
@recipe_ingredients = RecipeIngredient.find(params[:item_id])
end
配方成分的索引页面如下所示。我需要过滤配方成分索引页面上显示的数据,只是为了匹配作为URL中的参数收到的item_id。
<p id="notice"><%= notice %></p>
<h1>Recipe Ingredients</h1>
<table>
<thead>
<tr>
<th>Item</th>
<th>Ingredient</th>
<th>Quantity</th>
<th>Unit</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @recipe_ingredients.each do |recipe_ingredient| %>
<tr>
<td><%= recipe_ingredient.item.item %></td>
<td><%= recipe_ingredient.ingredient.ingredient %></td>
<td><%= recipe_ingredient.quantity %></td>
<td><%= recipe_ingredient.ingredient.recipe_unit %></td>
<td><%= link_to 'Show', recipe_ingredient %></td>
<td><%= link_to 'Edit', edit_recipe_ingredient_path(recipe_ingredient) %></td>
<td><%= link_to 'Destroy', recipe_ingredient, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Recipe Ingredient', new_recipe_ingredient_path %>
<%= link_to 'Back', '/items' %>
现在我收到此错误:
未定义的方法`show&#39;对于#&lt; RecipeIngredient:0xa5653b8&GT;
答案 0 :(得分:1)
@recipe_ingredients = RecipeIngredient.find(params[:item_id])
这将只返回一个RecipeIngredient
id = params[:item_id]
非活动记录数组
如果您要循环find
where
更改为@recipe_ingredients
@recipe_ingredients = RecipeIngredient.where(params[:item_id])
或者,您需要更改视图
<tbody>
<tr>
<td><%= @recipe_ingredients.item.item %></td>
<td><%= @recipe_ingredients.ingredient.ingredient %></td>
<td><%= @recipe_ingredients.quantity %></td>
<td><%= @recipe_ingredients.ingredient.recipe_unit %></td>
<td><%= link_to 'Show', @recipe_ingredients %></td>
<td><%= link_to 'Edit', edit_recipe_ingredient_path(@recipe_ingredients) %></td>
<td><%= link_to 'Destroy', @recipe_ingredients, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</tbody>