rails 3质量分配错误,简单但无法解决

时间:2013-06-21 14:56:28

标签: ruby-on-rails forms ruby-on-rails-3.2 mass-assignment

我一直在试图弄清楚为什么当我的代码看起来正确时我会继续接收质量分配错误。我使用了错误的语法吗?我真的很感激任何测试版,我一直在尝试调试我的应用程序的这么简单的部分,它真的停止了我的进展。我有以下内容:

控制器

class ProductsController < ApplicationController
def new
        @product =Product.new
end

def create
        @product = Product.new(params[:product])
end

end

模型

class Product < ActiveRecord::Base
  attr_accessible :name, :colors_attributes
  has_many :colors
  accepts_nested_attributes_for :colors, allow_destroy: true
end

class Color < ActiveRecord::Base
        attr_accessible :name, :product_id
        belongs_to :product
end

迁移

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateColors < ActiveRecord::Migration
  def change
    create_table :colors do |t|
      t.integer :product_id
      t.string :name

      t.timestamps
    end
  end
end

浏览

产品/ new.html.erb

 <%= render "form" %>

products / _form.html.erb

<%= form_for @product do |f| %>
        <%= f.text_field :name %>
        <%= f.fields_for :color do |c| %>
                <%= render 'color_fields', f: c %>
        <% end %>
        <%= f.button :submit %>
<% end %>

产品/ _color_fields.html.erb

<%= f.text_field :name %>

错误:

ActiveModel::MassAssignmentSecurity::Error in ProductsController#create

Can't mass-assign protected attributes: color

完整追踪:

activemodel (3.2.3) lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
activemodel (3.2.3) lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
activemodel (3.2.3) lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
activemodel (3.2.3) lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
activerecord (3.2.3) lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
activerecord (3.2.3) lib/active_record/base.rb:498:in `initialize'
app/controllers/products_controller.rb:7:in `new'
app/controllers/products_controller.rb:7:in `create'
actionpack (3.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.3) lib/abstract_controller/base.rb:167:in `process_action'
...

任何见解都将受到赞赏

1 个答案:

答案 0 :(得分:0)

我相信这就是你想要的

<%= form_for @product do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :colors do |c| %>
    <%= render 'color_fields', f: c %>
  <% end %>
  <%= f.button :submit %>
<% end %>

您的fields_for使用:color代替:colors