2011-09-28 62 views
2

我正在尝试使用accepts_nested_attributes来创建一个复杂的表单。基于该Nested Attributes文档,examples,等等,我已经建立了模型,像这样:accepted_nested_attributes_for undefined方法错误

用户模式:

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 

鸭型号:

class Duck < ActiveRecord::Base 
    belongs_to :user 
    accepts_nested_attributes_for :user 
end 

但是,当我尝试访问控制台中的嵌套属性,我得到

ruby-1.9.2-p290 :003 > User.first.ducks_attributes 
NoMethodError: undefined method `ducks_attributes' for #<User:0x007ffc63e996e0> 
    from ~/.rvm/gems/[email protected]/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:392:in `method_missing' 
    from ~/.rvm/gems/[email protected]/gems/activerecord-3.0.9/lib/active_record/attribute_methods.rb:46:in `method_missing' 
    from (irb):3 
    from ~/.rvm/gems/[email protected]/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start' 
    from ~/.rvm/gems/[email protected]/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start' 
    from ~/.rvm/gems/[email protected]/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>' 

什么我做错了吗?提前谢谢了。

+0

FWIW,我正在使用Rails 3.0.9 – Dan

回答

2

仅定义了属性书写器

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" } ] 
+0

谢谢,Molf-就是这样。 – Dan