Search code examples
ruby-on-railsruby-on-rails-3mass-assignment

Rails - Accepts_nested_attributes_for mass assignment error


I am currently trying to set up a form with nested fields on a belongs_to relationship, but I am running into a mass assignment error. My code so far is as follows (some html removed):

Sale model:

class Sale < ActiveRecord::Base
  attr_accessible :customer_attributes
  belongs_to :customer
  accepts_nested_attributes_for :customer
end

new.html.erb:

<div class="container">
  <%= form_for :sale, :url => sales_path do |sale| -%>
    <%= sale.fields_for :customer do |customer_builder| %>
      <%= render :partial => "customers/form", :locals => {:customer => customer_builder, :form_actions_visible => false} %>
    <% end -%>
  <% end -%>

customers/_form.html.erb

<fieldset>
  <label class="control-label">Customer Type</label>
  <%= collection_select(:customer, :customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %>
</fieldset>

I believe this should allow me to create a Sale object, and a nested Customer object. The parameters being sent are (note some unrelated params are included):

{"utf8"=>"✓",
"authenticity_token"=>"qCjHoU9lO8VS060dXFHak+OMoE/GkTMZckO0c5SZLUU=",
"customer"=>{"customer_type_id"=>"1"},
"sale"=>{"customer"=>{"features_attributes"=>{"feature_type_id"=>"1",
"value"=>"jimmy"}}},
"vehicle"=>{"trim_id"=>"1",
"model_year_id"=>"1"}}

The error I am getting is:

Can't mass-assign protected attributes: customer

I can see why this might be the case, since :customer is not in the attr_accessible list for Sale - though shouldn't the form be sending customer_attributes instead of customer?

Any help / advice appreciated.

EDIT 1: As far as I can tell, attr_accessible in the Sale model should be covered with :customer_attributes - if anyone says different, please let me know.

EDIT 2: I have tried various permutations, but I can not seem to get the parameters to send customer_attributes instead of simply customer - perhaps I have missed a tag or used an incorrect tag somewhere in the forms above?

EDIT 3: I have found another question on SO that indicated a problem with the :url => part on the form_for tag - the question was referring to a formtastic setup, but I'm wondering if that could be what is causing the problem here?


Solution

  • I got to the answer here eventually. The key was this line:

    <%= collection_select(:customer, :customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %>
    

    which needed to be changed to:

    <%= customer.collection_select(:customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %>
    

    Once this was changed, everything fell into place.