我有一个名为“User”的模型,它与“Address”模型有很多关联。
当我执行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
答案 0 :(得分:2)
after_initialize
钩子可以满足您的目的
class Address < ActiveRecord::Base
attr_accessor :test
after_initialize :init
def init
@test = "manu"
end
end
答案 1 :(得分:1)
建议不要覆盖ActiveRecord继承类的initialize方法。
如果要添加自定义初始化,请使用after_initialize
回调。查看所有ActiveRecord callbacks的rails api。