开发者

How to pass more than one constructor argument in a build_association call in Rails 3?

开发者 https://www.devze.com 2023-03-13 00:18 出处:网络
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 wh

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消