build_foo调用中的第二个参数永远不会进入Foo#initialize
(即args[1]
是nil
)。任何建议,以便在保持Foo#initialize
初始化的唯一参数的同时将两个或多个参数传递到*args
?
class Foo < ActiveRecord::Base
belongs_to :bar
def initialize *args
super()
self.total = args[0] + args[1]
end
end
class Bar < ActiveRecord::Base
has_one :foo
def do_something
build_foo 2, 3 # 3 never reaches Foo#initialize
build_foo [2,3] # args[0] == [2,3], which is not what's desired
save!
end
end
答案 0 :(得分:3)
要回答你的问题 - 你不能。只是因为build_foo只有documentation中定义的一个参数,即arguments = {}
,所以你应该只传递参数hash来初始化你的新记录。
此外,您无需在#super
中调用#initialize
,因为AR :: Base本身并未定义#initialize
。
为什么需要传递2个不同的参数而不是参数hash?位置参数不会告诉您设置的值,而对于AR对象,您可能在表中有多个属性。