2011-09-15 45 views
3

我有一個名爲「用戶」的模型,有許多關聯到「地址」模型。Rails Active Record - 如何在關聯模型中存在初始化方法時使用構建?

當我做User.new.addresses.build,我收到以下錯誤,

ArgumentError: wrong number of arguments (1 for 0) 
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `initialize' 
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `new' 
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `build_association' 
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:423:in `build_record' 
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:102:in `build' 
    from (irb):10 

這發生在我的地址添加到模型的初始化方法。

任何幫助,高度讚賞...

編輯:

沒有參數初始化方法,它看起來像這樣

class Address < ActiveRecord::Base 
    attr_accessor :test 

    def initialize 
    test = "manu" 
    end 
end 

回答

1

它不建議重寫初始化方法ActiveRecord繼承類。 如果您想添加自定義初始化,請使用after_initialize回調。請參閱所有ActiveRecord callbacks的導軌api。

2

after_initialize勾應成爲你的目的

class Address < ActiveRecord::Base 
    attr_accessor :test 
    after_initialize :init 

    def init 
    @test = "manu" 
    end 
end 
相關問題