2013-02-23 62 views
0

我有一個模型用戶約40表單域。然後我有3個屬於Child模型的字段。他們是:年齡,:性別,:家庭。如何使用accept_nested_attributes_for保存模型?

我看了一下accept_nested_attributes_for的文檔,對於如何將一個Child模型保存到數據庫有點困惑。

在我UsersController我有以下幾點:

@user = User.new(params[:user]) 
... 
@user.save 

現在Rails文檔中,他們有一個名爲成員模型和它裏面,它的has_many:職位和accepts_nested_attributes_for:帖子。他們像這樣保存成員模型:

params = { :member => { 
    :name => 'joe', :posts_attributes => [ 
    { :title => 'Kari, the awesome Ruby documentation browser!' }, 
    { :title => 'The egalitarian assumption of the modern citizen' }, 
    { :title => '', :_destroy => '1' } # this will be ignored 
    ] 
}} 

member = Member.create(params['member']) 

但是我已經有params [:member]與params [:user]等效。我的3個孩子領域:年齡,性別和家庭參與度[:年齡],參數[:性別]和參數[:家庭]。所以我想我的問題是如何保存一個用戶模型,並有3個子字段保存在子模型中?

回答

0

您需要正確設置表格才能使用accepts_nested_attributes_for

因此,在你User模式,你必須:

accepts_nested_attributes_for :child 

,並在您的形式,你可以這樣做:

form_for @user do |f| 
    f.text_field :name #or whatever your user attributes 

    f.fields_for :child, @user.build_child do |child| 
    child.text_field :age 
    #etc 
    end 
end 

現在應該軌道建設child對象的一部分user對象,並且您應該可以一次創建對象userchild

無論你把childchildrenaccepts_nested_attributes_for完全取決於userchild之間的關係。如果user只是has_one :child,那麼以上就應該足夠了。如果它是一個has_many關係,你需要的符號改變爲:children,改變@user.build_child@user.children.build.

另外,不要忘記添加(child|children)_attributesattr_accessibleuser模型,否則你將無法通過表單提交進行批量分配。

+0

謝謝@Zajn。這解釋了很多。但我想我忽略了我的問題的一個主要部分。這些子字段是動態生成的,具體取決於用戶指定的子女數量。那麼,我會像這樣保存Child字段嗎? @ user.children.build(年齡:params [:age1],性別:params [:gender1],home:params [:home1]) – mikeglaz 2013-02-23 23:13:15

+0

是的,這個工程! – mikeglaz 2013-02-24 18:03:44