Updating nested attributes causes duplicate entries

Posted by params_noob on Stack Overflow See other posts from Stack Overflow or by params_noob
Published on 2014-05-30T03:21:47Z Indexed on 2014/05/30 3:25 UTC
Read the original article Hit count: 194

I have a has_many and belongs_to relationship between Job and Address.

When I try to update Job and Address in the same form, it updates job but creates a duplicate entry for Address.

Am I missing something here?

The Edit and Update Actions from Jobs:

def edit
  @job = Job.find(params[:id])
end

def update
  @job = Job.find(params[:id]) 
if @job.update_attributes(job_params)
  flash[:success] = "Job Updated"
  redirect_to current_user
else
  render 'edit'
  end
end

The edit form:

<h1>Edit Job Information</h1>

<div class="row">
  <div class="span6 offset3">
  <%= form_for(@job) do |f| %>
  <%= render 'shared/error_messages' %>
  <%= f.label :recipient %>
  <%= f.text_field :recipient %>

  <%= f.label :age %>
  <%= f.text_field :age %>

  <%= f.label :gender %>
  <%= f.text_field :gender %>

  <%= f.label :ethnicity %>
  <%= f.text_field :ethnicity %>

  <%= f.label :height %>
  <%= f.text_field :height %>

  <%= f.label :weight %>
  <%= f.text_field :weight %>

  <%= f.label :hair %>
  <%= f.text_field :hair %>

  <%= f.label :eyes %>
  <%= f.text_field :eyes %>

  <%= f.label :other_info %>
  <%= f.text_field :other_info %>


  <h3> Address Information </h3>

  <%= f.fields_for :addresses do |address| %>
  <%= address.label :label, "Label" %>
  <%= address.text_field :label %>

  <%= address.label :addy, "Address" %>
  <%= address.text_field :addy %>

  <%= address.label :apt, "Apt/Suite/etc" %>
  <%= address.text_field :apt %>

  <%= address.label :city, "City" %>
  <%= address.text_field :city %>

  <%= address.label :state, "State" %>
  <%= address.text_field :state %>

  <%= address.label :zip, "Zip code" %>
  <%= address.text_field :zip %>

  <% end %>




  <%= f.label :instructions, "Service Instructions" %>
  <%= f.text_field :instructions %>

  <%= check_box_tag(:rush) %>
  <%= label_tag(:rush, "Rush?") %>



  <%= f.submit "Update Job", class: "btn btn-large btn-primary" %>
  <% end %>
   </div>
  </div>

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about nested-forms