gpt4 book ai didi

ruby-on-rails - Rails Active Record - 当关联模型中有初始化方法时如何使用构建?

转载 作者:行者123 更新时间:2023-12-04 06:05:06 25 4
gpt4 key购买 nike

我有一个名为“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

当我在 Address 模型中添加初始化方法时会发生这种情况。

非常感谢任何帮助...

编辑:

初始化方法没有参数,看起来像这样

class Address < ActiveRecord::Base
attr_accessor :test

def initialize
test = "manu"
end
end

最佳答案

after_initialize Hook 应该可以满足您的目的

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

def init
@test = "manu"
end
end

关于ruby-on-rails - Rails Active Record - 当关联模型中有初始化方法时如何使用构建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7427721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com