build_foo调用中的第二个参数绝不会将其设置为Foo#initialize
(即args[1]
为nil
)。任何建议,以获得两个或更多的参数传递到Foo#initialize
,同时保持*args
初始化的唯一参数?如何在Rails 3的build_association调用中传递多个构造函数参数?
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
为了您的方便:http://guides.rubyonrails.org/association_basics.html#detailed-association-reference – 2011-06-14 06:42:55