2011-09-28 44 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