[英]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.