如何在 Rails 3 的 build_association 调用中传递多个构造函数参数?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回答你的问题——你不能。仅仅是因为 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.