Nested object forms do not work properly

I am trying to get nested model forms . As far as I can tell, I'm doing everything right, but it still doesn't work.

I'm on Rails 3 beta 3.

My models 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

Am I doing something wrong here? Or is there a problem in the beta version of Rails 3?

Update

This is a mistake caused attr_accessible :namein the Recipe. This is not Rails3.

+3
source share
3 answers

? , , - .

, , ingredients_attributes attr_accessible.

+3

: attr_accessible :name components_attributes (, , ). , . , Rails 2.3.2.

, ...

+1

, Rails 3; Railscast 2.3, 3.0, . , - .

0

Source: https://habr.com/ru/post/1746799/


All Articles