I'm trying to use accepts_nested_attributes to create a complex form. Based on the Nested Attributes documentation, examples, etc., I've set up the models like so:
User model:
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password,
:password_confirmation, :ducks_attributes
has_many :ducks, :class_name => 'Duck'
accepts_nested_attributes_for :ducks
.
.
.
end
Duck model:
class Duck < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
But when I try to access the nested attributes in the console, I get
ruby-1.9.2-p290 :003 > User.first.ducks_attributes
NoMethodError: undefined method `ducks_attributes' for #<User:0x007ffc63e996e0>
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:392:in `method_missing'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activerecord-3.0.9/lib/active_record/attribute_metho开发者_JS百科ds.rb:46:in `method_missing'
from (irb):3
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
What am I doing wrong? Many thanks in advance.
Only the attribute writer is defined.
class User < ActiveRecord::Base
has_many :ducks
accepts_nested_attributes_for :ducks
end
class Duck < ActiveRecord::Base
belongs_to :user
end
# This works:
User.first.ducks_attributes = [ { :name => "Donald" } ]
# This is more common (attributes posted from a form):
User.create :ducks_attributes => [ { :name => "Donald" }, { :name => "Dewey" } ]
精彩评论