开发者

Nested Object Forms not working as expected

I'm trying to get a nested model forms view working. As far as I can tell I'm doing everything right, but it still does not work.

I'm on Rails 3 beta 3.

My models are as expected:

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

I can use Recipe.ingredients_attributes= as expected:

recipe = Recipe.new
recipe.ingredients_attributes = [ {:name=>"flour", :amount=>"1 cup"}, {:name=>"sugar", :amount=>"2 cups"}]
recipe.ingredients.size    # -> 2; ingredients contains expected instances

However, I cannot create new object graphs using a hash of parameters 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

Is there something I'm doing wrong here? Or is there a problem in the Rails 3 beta?

Update

It's a bug caused by attr_accessible :name in Recipe. It's not Rails3 specific.


Have you tried saving the record and still get no ingredients? From your example above, there's no save, so I don't believe recipe has any ingredients, yet.

In response to your answer below, I believe you could add ingredients_attributes as an attr_accessible.


I've found the answer: the presence of attr_accessible :name in recipe will break the ingredients_attributes (and thus the nested model forms). Remove it and everything works fine. I've verified that this bug exists at least as far back as Rails 2.3.2.

Off to submit a bug report...


I've verified that it's not a Rails 3 bug; I built the Railscast example in both 2.3 and 3.0 and it works as advertised in both cases. That means that it's something to do with my code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜