【问题标题】:How to pass more than one constructor argument in a build_association call in Rails 3?如何在 Rails 3 的 build_association 调用中传递多个构造函数参数?
【发布时间】:2011-06-14 06:33:40
【问题描述】:

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

【问题讨论】:

标签: ruby-on-rails activerecord has-one model-associations


【解决方案1】:

回答你的问题 - 你不能。只是因为 build_foo 在documentation 中只定义了一个参数,即arguments = {},所以你应该只传递参数散列来初始化你的新记录。

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

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

【讨论】:

  • 谢谢 MBO。在实际代码中(与上面显示的简化版本相比),我在没有参数哈希的情况下做得很好,因为参数都是不同用户定义类的实例(即 args[n].is_a?ClassA, args[m]. is_a? ClassB 等)。参数位置并不重要,因为我可以通过 is_a?并因此确定它是哪个论点。但现在鉴于您的解释,我将考虑采用参数 {}。感谢您的帮助。
猜你喜欢
  • 2012-11-03
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 2013-02-17
  • 2015-01-13
  • 1970-01-01
相关资源
最近更新 更多