The second argument in the build_foo call never makes it into Foo#initialize
(i.e. args[1]
is nil
开发者_StackOverflow). Any suggestions so as to get two or more arguments passed into Foo#initialize
while keeping *args
the only argument to initialize?
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
To answer your question - you can't. Simply because build_foo has only one parameter defined in documentation, which is arguments = {}
, so you should pass there only arguments hash to initialize your new record.
Also you don't need to call #super
in #initialize
, as AR::Base doesn't define #initialize
itself.
Why do you need to pass 2 distinct arguments instead of arguments hash? Positional arguments doesn't tell you which value you set, and with AR objects you probably has more than one attribute in table.
精彩评论