如何在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
    
已邀请:
        要回答您的问题-您不能。仅仅因为build_foo在文档中定义的参数只有一个,即
arguments = {}
,所以您应该仅在其中传递参数hash来初始化新记录。 同样,您也不需要在
#initialize
中调用
#super
,因为AR :: Base没有定义
#initialize
本身。 为什么需要传递2个不同的参数而不是参数哈希?位置参数不会告诉您所设置的值,而对于AR对象,表中可能具有多个属性。     

要回复问题请先登录注册