2012-12-26 49 views
0

調用Model.create時覆蓋initialize方法的正確方法是什麼?我想:調用Model.create時,覆蓋initialize方法的正確方法是什麼?

Model < ActiveRecord::Base 
    def initialize params, foo 

意欲它被稱爲是這樣的:

Model.create foo:'bar' 

不使用Rails,但使用ActiveRecord。

+0

你想實現什麼? –

+0

我意識到這個問題措辭不當。我真正想知道的是如何覆蓋'create'方法。 –

+0

@BSeven可以請您提供一個具體的例子,說明如何使用被覆蓋的'create'? –

回答

3

最好遠離那條路!

如果你需要一個不同的行爲創建一個模型對象只需創建一個不同的方法,如:

class Model < ActiveRecord::Base 
    def self.create_with_foo params, foo 
    model = self.new params 
    # Do whatever you want with foo for example 
    model.foo = true if foo == :foo 
    model.save 
    model # return the created model object 
    end 
end 
0

foo: 'bar'是一個參數:哈希。它是{foo: 'bar'}的簡寫,它是{:foo => 'bar'}的簡寫。所以如果你想像那樣使用它,你只需要定義它,以便它需要一個參數。

相關問題