2011-05-09 59 views

回答

3

accepts_nested_attributes_for只是一個捷徑。它定義了一個動態屬性{field_name}_attributes,這樣如果你有一個表單,你可以包含嵌套屬性並讓它自動將它們分配給一個關聯。像這樣:

form_for :object do |f| 
    f.text_field :attr1 
    f.text_field :attr2 
    f.fields_for :association_attributes do |g| 
    g.text_field :nested1 
    g.text_field :nested2 
    end 
end 

這個帖子與參數{object: {attr1: val, attr2: val, association_attributes: {nested1: val, nested2: val}}並添加accepts_nested_attributes_for :association到類,使整個事情的工作沒有任何額外的代碼。

+0

因此,使用你的表單,但用我的例子,沒有「accep_nested_attributes_for」,我必須在控制器中調用兩次params([:object]和[:object] [:association])? – 2011-05-09 21:01:34

+1

好吧,如果沒有'accep_nested_attributes_for'和這種形式,你會得到一個錯誤「Undefined method association_attributes = object object」。爲了使它工作,你需要從'params [:object] .except(:association_attributes)'創建對象,然後從'object.associations.new(params [:object] [:association_attributes])創建關聯'。 – 2011-05-09 21:54:46

+1

您不必做:association_attributes,只需在模型中與'accep_nested_attributes_for'的':association'自動創建名爲'association_attributes'的屬性。 – 2011-05-09 22:19:36

相關問題