3

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I did actually try saving and not-saving, but neither made a difference.
1

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...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.