2011-01-14 59 views
0

簡單的Rails問題。我有一個模型美孚它看起來像這樣:紅寶石上的繼承類 - monkeypatching/overriding belongs_to

class Foo < ActiveRecord::Base 

    belongs_to :bar 

    def self.belongs_to(association_id, options = {}) 
    puts "HI" 
    super 
    end 
end 

爲什麼當我在IRB

>> Foo 
=> Foo(id: integer, bar_id: integer) 
>> 

加載美孚我沒有看到「HI」(我相當肯定的Rails調用belongs_to的時該類被加載)?然而,當我輸入Foo.belongs_to(「anything_here」),我看到:

>> Foo.belongs_to("anything_here") 
HI 
=> nil 
>> 

回答

1

不能完全確定你所要完成的(看起來有點討厭!)。

無論哪種方式,雖然定義的順序和呼叫事情:

class Foo < ActiveRecord::Base 
    def self.belongs_to(association_id, options = {}) 
    puts "HI" 
    super 
    end 

    belongs_to :bar 
end
+0

只是想了解繼承和方法重載的相互作用。謝謝。這回答了我的問題。 – 2011-01-14 19:40:05