我使用脚手架生成开始我的应用程序:
rails g scaffold Category title
rails g scaffold Product category:references title
rake db:migrate
我启动了服务器并创建了一个新类别,然后我想使用id
1
添加一个新产品到这个类别,但当我检查日志时:
Started POST "/products" for 127.0.0.1 at 2014-08-01 09:28:16 +0430
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dd7tvD/DrXf1SiAnCR6ZUvtwQzVuy39HG4A9dmo7Gms=", "product"=>{"category"=>"1", "title"=>"Rails"}, "commit"=>"Create Product"}
Unpermitted parameters: category
产品控制器的允许参数中有category_id
:
def product_params
params.require(:product).permit(:category_id, :title)
end
修改:
型号:
class Product < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
end
产品形式:
<%= 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 :catagory %><br>
<%= f.text_field :catagory %>
</div>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
你能帮帮我吗?我做错了什么?
答案 0 :(得分:1)
在form_for
标记中,您必须有category_id
字段,而不是category
字段(我不确定您为什么要向用户询问category_id
)。
<%= f.label :catagory_id %><br>
<%= f.text_field :catagory_id %>
除了答案之外,products
和category
之间的关联不合适。您遗失了has_many
。
您的category
模型应如下所示:
class Category < ActiveRecord::Base
has_many :products
end