2013-06-20 132 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