简体   繁体   中英

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

The second argument in the build_foo call never makes it into Foo#initialize (ie args[1] is nil ). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM