好的,我已经问过类似的问题,但这是视图的问题。我已经使用form_玩了几个小时,不能完全正确。想知道是否有人可以指出obvioius错误...
/products/new.html.erb:
<h1>New Product</h1>
<%= form_for :product, as: :post, url: category_product_path(:product) do |form| %>
<% 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 |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :category_id %>
<%= form.text_field :category_id %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
<%= link_to 'Back', category_products_path %>
和我的route.rb:
category_products GET /categories/:category_id /products(.:format) products#index
POST /categories/:category_id/products(.:format) products#create
new_category_product GET /categories/:category_id/products/new(.:format) products#new
edit_category_product GET /categories/:category_id/products/:id/edit(.:format) products#edit
category_product GET /categories/:category_id/products/:id(.:format) products#show
PATCH /categories/:category_id/products/:id(.:format) products#update
PUT /categories/:category_id/products/:id(.:format) products#update
DELETE /categories/:category_id/products/:id(.:format) products#destroy
categories GET /categories(.:format) categories#index
POST /categories(.:format) categories#create
new_category GET /categories/new(.:format) categories#new
edit_category GET /categories/:id/edit(.:format) categories#edit
category GET /categories/:id(.:format) categories#show
PATCH /categories/:id(.:format) categories#update
PUT /categories/:id(.:format) categories#update
DELETE /categories/:id(.:format) categories#destroy
和错误消息:
ActionView::Template::Error (No route matches {:action=>"show", :category_id=>:product, :controller=>"products"}, missing required keys: [:id])
不是在迁移发生时创建的column:id-我有一个典型的迁移文件,其中包含t.string:name和t.text:description,仅此而已。
答案 0 :(得分:0)
您的form_for
网址错误。您应该使用指向products#create
的路由,该路由还具有在表单中使用的POST
动词
<%= form_for :product, as: :post, url: category_products_path do |form| %>