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

发布于 2024-11-15 16:27:09 字数 592 浏览 6 评论 0原文

build_foo 调用中的第二个参数永远不会进入 Foo#initialize (即 args[1]nil)。有什么建议可以将两个或多个参数传递到 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

The second argument in the build_foo call never makes it into Foo#initialize (i.e. 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵山崖 2024-11-22 16:27:09

回答你的问题——你不能。仅仅是因为 build_foo 在文档,即 arguments = {},因此您应该只传递参数哈希来初始化新记录。

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文