2
什麼時候應該使用「accep_nested_attributes_for」?在下面的示例中,我可以在User模型中執行成功的「user.microposts.create」而不需要「accep_nested_attributes_for」。爲什麼在可以通過父級保存時使用「acceptable_nested_attributes_for」?
class Micropost < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :microposts
end
因此,使用你的表單,但用我的例子,沒有「accep_nested_attributes_for」,我必須在控制器中調用兩次params([:object]和[:object] [:association])? – 2011-05-09 21:01:34
好吧,如果沒有'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
您不必做:association_attributes,只需在模型中與'accep_nested_attributes_for'的':association'自動創建名爲'association_attributes'的屬性。 – 2011-05-09 22:19:36