繁体   English   中英

如何在 Rails 3 的 build_association 调用中传递多个构造函数参数?

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

build_foo 调用中的第二个参数永远不会进入Foo#initialize (即args[1]nil )。 有什么建议可以让两个或更多 arguments 传递到Foo#initialize中,同时保持*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 = {} ,所以你应该只传递 arguments hash 来初始化你的新记录。

此外,您不需要在#initialize中调用#super ,因为 AR::Base 本身没有定义#initialize

为什么需要传递 2 个不同的 arguments 而不是 arguments hash? 位置 arguments 不会告诉您设置了哪个值,并且对于 AR 对象,您可能在表中具有多个属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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