如何在Rails 3的build_association调用中传递多个构造函数参数?
|
build_foo调用中的第二个参数从不将其变为
Foo#initialize
(即args[1]
为nil
)。有什么建议可以使两个或多个参数传递到ѭ0中,同时让*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
没有找到相关结果
已邀请:
1 个回复
烷刨画颠离
,所以您应该仅在其中传递参数hash来初始化新记录。 同样,您也不需要在
中调用
,因为AR :: Base没有定义
本身。 为什么需要传递2个不同的参数而不是参数哈希?位置参数不会告诉您所设置的值,而对于AR对象,表中可能具有多个属性。