I have been trying to figure out why I keep receiving mass-assignment errors when my code seems to be correct. Am I using the wrong syntax? I would really appreciate any beta, I have been trying to debug such a simple part of my application and its really halting my progress. I have the following:
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
products/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 %>
products/_color_fields.html.erb
<%= f.text_field :name %>
Error:
ActiveModel::MassAssignmentSecurity::Error in ProductsController#create
Can't mass-assign protected attributes: color
Full trace:
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'
...
any insight would be appreciated
I believe this is what you want
<%= 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 %>
Your fields_for
was using :color
instead of :colors