更新对象belongs_to association创建新对象

时间:2013-06-20 11:44:38

标签: ruby-on-rails ruby

我有一个与belongs_tolocation关联的Event对象:

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

在我的活动表单中,我使用嵌套属性来显示位置表单。来自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 %>

我按如下方式创建一个新事件:

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

但是,当我编辑这个新创建的记录的位置时,位置记录不会被编辑,而是在数据库中插入新的位置记录。

我的问题是,如何确保在编辑位置时(从父级事件表单),它将更新属于该位置对象的属性,而不是创建新的位置对象。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,就是将:update_only => true添加到关联中。模型代码变为:

class Event < ActiveRecord::Base
  belongs_to :location, :update_only => true  
  accepts_nested_attributes_for :location
end
相关问题