2013-06-20 131 views
1

我有一个belongs_to关联事件对象location更新对象关联belongs_to的创建新对象

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

以我事件形式I使用嵌套的属性来显示位置的形式。从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 

然而,当我修改这个新创建的记录的位置,位置记录不会被编辑,而是将新的位置记录插入到数据库中。

我的问题是,如何确保在编辑位置(从父Event窗体)时,它将更新属于位置对象的属性,而不是创建新的Location对象。

+0

快速的问题位置有许多事件中,粘贴您的视图code.Do你想要的位置应该在每一个事件或创建事件位置创建应该从现有的 – Amar

+0

用户可以选择选择列表中的位置。如果该位置尚未存在,则应该创建该位置。如果它在列表中,则只应保存关联。 –

+0

你的'Location'类是否有一个根据'has_many:events'或'has_one:event'在里面? – rudolph9

回答

1

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

class Event < ActiveRecord::Base 
    belongs_to :location, :update_only => true 
    accepts_nested_attributes_for :location 
end 
+1

我认为':update_only'需要被赋予'accepting_nested_attributes_for'而不是'belongs_to'。 – peter