1

I have an Event object with a belongs_to association to location:

class Event < ActiveRecord::Base
  belongs_to :location
  accepts_nested_attributes_for :location  
end

In my Event form I use nested attributes to display the location form. Relevant bit for location form from events/_form.html.erb:

<%= f.fields_for :location do |lf| %>  
  <%= f.label 'Location', :class => 'control-label' %>
  <%= lf.text_field :name  %>
  <%= lf.text_field :address %>
<% end %>

I create a new Event as follows:

  def new
    @event = Event.new
    @event.build_location
  end

However, when I edit the location of this newly created record, the location record does not get edited, instead a new location record gets inserted in the database.

My question is, how do I make sure that upon editing a location (from the parent Event form), it will update the attributes belonging to the location object instead of creating a new Location object.

4

1 回答 1

1

我找到了解决方案,它是通过添加:update_only => true到关联。该模型的代码变为:

class Event < ActiveRecord::Base
  belongs_to :location, :update_only => true  
  accepts_nested_attributes_for :location
end
于 2013-06-20T13:20:35.457 回答