Nested Object Forms not working as expected

Posted by Craig Walker on Stack Overflow See other posts from Stack Overflow or by Craig Walker
Published on 2010-05-23T23:02:29Z Indexed on 2010/05/23 23:30 UTC
Read the original article Hit count: 385

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby