简单rails应用程序中未允许的参数

时间:2014-08-01 05:16:28

标签: ruby-on-rails ruby-on-rails-4

我使用脚手架生成开始我的应用程序:

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 %>
你能帮帮我吗?我做错了什么?

1 个答案:

答案 0 :(得分:1)

form_for标记中,您必须有category_id字段,而不是category字段(我不确定您为什么要向用户询问category_id )。

<%= f.label :catagory_id %><br>
<%= f.text_field :catagory_id %>

除了答案之外,productscategory之间的关联不合适。您遗失了has_many

您的category模型应如下所示:

class Category < ActiveRecord::Base
  has_many :products
end