[英]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
). build_foo 调用中的第二个参数永远不会进入Foo#initialize
(即args[1]
为nil
)。 Any suggestions so as to get two or more arguments passed into Foo#initialize
while keeping *args
the only argument to initialize?有什么建议可以让两个或更多 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
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.仅仅因为 build_foo 在文档中只定义了一个参数,即arguments = {}
,所以你应该只传递 arguments hash 来初始化你的新记录。
Also you don't need to call #super
in #initialize
, as AR::Base doesn't define #initialize
itself.此外,您不需要在#initialize
中调用#super
,因为 AR::Base 本身没有定义#initialize
。
Why do you need to pass 2 distinct arguments instead of arguments hash?为什么需要传递 2 个不同的 arguments 而不是 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.位置 arguments 不会告诉您设置了哪个值,并且对于 AR 对象,您可能在表中具有多个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.