我正在尝试使 nested model forms View 正常工作。据我所知,我做的一切都是正确的,但它仍然不起作用。
我在 Rails 3 beta 3 上。
我的模型符合预期:
class Recipe < ActiveRecord::Base
has_many :ingredients, :dependent => :destroy
accepts_nested_attributes_for :ingredients
attr_accessible :name
end
class Ingredient < ActiveRecord::Base
attr_accessible :name, :sort_order, :amount
belongs_to :recipe
end
我可以按预期使用 Recipe.ingredients_attributes=:
recipe = Recipe.new
recipe.ingredients_attributes = [ {:name=>"flour", :amount=>"1 cup"}, {:name=>"sugar", :amount=>"2 cups"}]
recipe.ingredients.size # -> 2; ingredients contains expected instances
但是,我无法使用参数 as shown in the documentation 的散列创建新的对象图:
params = { :name => "test", :ingredients_attributes => [ {:name=>"flour", :amount=>"1 cup"}, {:name=>"sugar", :amount=>"2 cups"}] }
recipe = Recipe.new(params)
recipe.name # -> "test"
recipe.ingredients # -> []; no ingredient instances in the collection
我在这里做错了吗?还是 Rails 3 beta 中存在问题?
更新
这是 Recipe 中的
attr_accessible :name
引起的错误。它不是特定于 Rails3 的。 最佳答案
您是否尝试过保存记录但仍然没有成分?从你上面的例子来看,没有保存,所以我不相信 recipe 有任何成分。
针对您在下面的回答,我相信您可以将 ingredients_attributes
添加为 attr_accessible
。
关于ruby-on-rails - 嵌套对象表单未按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2893857/