2011-09-28 76 views
0

我正在嘗試制定保存belongs_to記錄ID的最佳方式,同時創建新的子記錄。我目前使用隱藏字段來保留父母的ID。將belongs_to ID保存在表單中,而不使用隱藏字段?

你能想到一個更好的方法來完成這個父母的ID保存(不使用隱藏的領域)?

Here'a我的路線的一個片段:

resources :kids 
resources :parents do 
    resources :kids 
end 

這裏是我的父模型...

​​

這裏是我的孩子......模型

class Kid < ActiveRecord::Base 
    belongs_to :parent, :autosave => true 
end 

這是我創建一個新的孩子時的視圖形式...

<%= form_for(@kid) do |f| %> 
%= f.hidden_field :parent_id, :value => @parent.id %> 
<%= f.label :title, 'Title' %> 
<%= f.submit %> 
<% end %> 

然後把它傳遞給創建(POST)方法...

def create 
    @kid = Kid.new(params[:kid]) 
    @parent = Parent.find(@kid.parent_id) 
    @kid.save 
    # etc... 
end 

回答

3

相關聯。如果你把你的路由實例的第一行,只是

resources :parents do 
    resources :kids 
end 

現在你不有沒有父母調用KidsController的歧義。你的路由匹配的行爲就像

/parents/:parent_id/kids 

現在,在KidsController,你可以做

def create 
    @parent = Parent.find(params[:parent_id]) 
    @parent.kids.create(params[:kid]) 
    #... 
end 

新的孩子得到,當你通過的has_many收集

+0

很酷,非常感謝! – joecritch

0

如果你不想在把它作爲一個隱藏字段,我推薦使用nested resources,你可以請將parent_id保留在網址中,並將parents/1/kids作爲您的路徑。然後,在KidsController,你需要加載你的父資源,並將其與Kid

1

是嵌套創建它分配其母公司汽車資源是最好的方式之一,但在你的情況下,你也可以使用「field_for」。

+0

有趣的,我會研究這個 – joecritch

相關問題