jeudi 28 janvier 2016

undefined method `name' for nil:NilClass when deleting association

I am using Rails 3.2.13 I have 3 entities

Mother

class Mother < ActiveRecord::Base
    attr_accessible :previous_births_attributes
    belongs_to :participant
    has_many :previous_births
    accepts_nested_attributes_for :previous_births, :reject_if => :all_blank, allow_destroy: true
end

PreviousBirth

class PreviousBirth < ActiveRecord::Base
  attr_accessible :gender
  belongs_to :mother
end    

I displayed my view using cocoon

_form.html.erb

<div id='previous-births'>
  <%= f.simple_fields_for :previous_births do |task| %>
      <%= render 'previous_birth_fields', :f => task %>
  <% end %>
  <%= link_to_add_association 'add previous birth', f, :previous_births, class: 'btn btn-success btn-mini ' %>      
</div>

_previous_birth_fields.html.erb

<div class="nested-fields row">
  <table class="table table-compact span12">
    <thead>
     <tr>
       <th class="span1">Gender</th>
       <th class="span1">&nbsp;</th>
     </tr>
  </thead>
  <tbody>
    <tr>
      <td><%= f.input_field :gender, collection: ["Female", "Male"], :class => "span1" %></td>
      <td><%= link_to_remove_association "remove", f, class: 'btn btn-danger btn-small span1' %></td>
    </tr>
  </tbody>

Adding previous_birth works like a charm. But when I remove association during update, I get

NoMethodError (undefined method name' for nil:NilClass): app/controllers/mothers_controller.rb:71:inblock in update' app/controllers/mothers_controller.rb:70:in `update'

mothers_controllers.rb

def update
  @mother = Mother.find(params[:id])
  participant = @mother.participant
  authorize participant
  respond_to do |format|
  if @mother.update_attributes(params[:mother]) #line 71
    format.html { redirect_to @mother.participant, notice: 'Mother was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @mother.errors, status: :unprocessable_entity }
  end
end

I do not have an attribute called name in either mother or previous birth entities. I tried to google it, but found nothing. Does anyone have any idea?

Thank you

Aucun commentaire:

Enregistrer un commentaire