Search code examples
ruby-on-railsnested-attributesmass-assignment

Mass-assignment error on nested attributes


I have an event which can have multiple occurrences (datetimes -- unfortunately, I've misspelled it in code as occurance) which can be dynamically added (thanks to Ryan Bates' awesome tutorial: http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast):

has_many :occurances, :dependent => :destroy
accepts_nested_attributes_for :occurance, :reject_if => lambda { |a| a[:when].blank? }, :allow_destroy => true'

 attr_accessible :occurances, :occurances_attributes, :occurance_id

Then the form:

.control-group.occurance_fields
  = f.label "Date & Time", :class => 'control-label'
  .controls
    = f.fields_for :occurance do |o_form|
      = o_form.text_field :when, :class => 'datepicker'

In the new method of the event_controller:

 @event.occurances.build

I currently have an issue when you submit the form:

Can't mass-assign protected attributes: occurance

If I add attr_accessible :occurance I get the following error:

unknown attribute: occurance

What am I missing here? I've looked at a few other questions regarding similar problems but I am unable to translate their solutions to my project.


Solution

  • attr_accessible: occurance_ids
    

    and

    accepts_nested_attributes_for :occurances, :reject_if => lambda { |a| a[:when].blank? }, :allow_destroy => true'
    

    Edit:

    You :occurance_id is also invalid in your :attr_accessible. Because it's a has_many relationship, the foreign key will be in the Occurances table.