我有类别和产品,类别中有很多产品。我可以编辑删除创建类别,也可以在每个类别中创建删除产品,但想要编辑每个产品。我可以使用 link_to 访问特定类别的单个产品,并且产品控制器正在接收特定类别的产品。
在类别的 html 中,所有产品都属于该类别
<%= link_to 'Edit', edit_category_product_path(product.category, product) %>
产品的控制器,编辑功能是
@product = Product.where(params[:id])
那么我的编辑html是
<%= form_for @product do |f| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Back', category_products_path %>
尝试编辑产品时出现此错误
NoMethodError in Products#edit
Showing C:/Sites/propoolpro6/app/views/products/edit.html.erb where line #3 raised:
undefined method `model_name' for ActiveRecord::Relation:Class
Extracted source (around line #3):
1: <h1>Editing product</h1>
2:
3: <%= form_for @product do |f| %>
4: <% if @product.errors.any? %>
5: <div id="error_explanation">
6: <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
Rails.root: C:/Sites/propoolpro6
Application Trace | Framework Trace | Full Trace
app/views/products/edit.html.erb:3:in `_app_views_products_edit_html_erb___584392485_32651052'
Request
Parameters:
{"category_id"=>"1",
"id"=>"3"}
注意:我用过这个 2,但同样的错误,
<%= form_for(@product) do |f| %>