Search code examples
ruby-on-railsrubynested-attributes

Edit nested attributes


I have a problem when I edit a nested model. When I execute the code bellow this create another entry in my WeeklySchedule table.

Example: I want to replace 9 to 10 in Monday.

WeeklySchedule table:

Before edit:

weekly_schedule_id: 1 monday: 9

After edit:

weekly_schedule_id: 1 monday: 9
weekly_schedule_id: 2 monday: 10

Code:

Models:

class Installation < ActiveRecord::Base
  accepts_nested_attributes_for :weekly_schedule
  belongs_to :weekly_schedule
end

class WeeklySchedule < ActiveRecord::Base
  has_one :installation
end

Form:

 <%= simple_form_for @installation, class: 'form-horizontal' do |f| %>
      <%= f.simple_fields_for :weekly_schedule do |w| %>
        <%= w.time_field :monday %>
      <% end %>
 <% end %>

Controller:

def update
 @installation.update(installation_params)
 (...)
end

def edit
 @installation = current_user.installations.find_by(:installation_id => params[:id])
end

installation_params:

{"x"=>"20",
 "y"=>"21",
"weekly_schedule_attributes"=>{"monday"=>"10"}}

What I am doing wrong?


Solution

  • This happens when you are missing :id in the strong parameters for the nested model. Make sure your installation_params includes :id like the following:

    def installation_params
      params.require(:installation).permit(..., :weekly_schedule_attributes => [:id, :monday, ...])
    end