0

我一直在试图弄清楚为什么当我的代码似乎正确时我不断收到批量分配错误。我使用了错误的语法吗?我真的很感激任何测试版,我一直在尝试调试我的应用程序中如此简单的部分,它真的阻碍了我的进步。我有以下内容:

控制器

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" %>

产品/_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'
...

任何见解将不胜感激

4

1 回答 1

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

于 2013-06-21T15:13:19.700 回答