2014-03-06 63 views
0

所以我跟在他們一些ActiveRecord對象,而如果它的事項,是在一個單表繼承層次結構中的寶石紅寶石的寶石和地方對象覆蓋

# gem 
class MySTIBaseClass < ActiveRecord::Base 
    # some code, does NOT implement a default_scope 
end 

當我在Rails應用程序試圖定義一個default_scope

class MySTIBaseClass < ActiveRecord::Base 
    default_scope :order => "my_sti_bases.name ASC" 
end 
class MySTIOtherClass < MySTIBaseClass 
    # this is not in the gem, only in the rails application 
    scope :active, { where active: true } 
end 
MySTIOtherClass.active # order default scope is not applied 

然而,如果不是重新打開類我把代碼中的初始化:

# initializer 
MySTIBaseClass.instance_eval do 
    default_scope :order => "my_sti_bases.name ASC" 
end 

# when the app is running 
MySTIOtherClass.active # default_scope is applied 

不過,我真的不能似乎明白了爲什麼是這種情況。看起來MySTIOtherClass.active在所有聲明已經被評估之前都沒有被調用,所以在應用程序中運行的類的版本應該能夠全面瞭解所有聲明的內容。有沒有衝突的default_scopes,它是選擇最後一個聲明,所以它看起來像默認範圍應該工作不管。

回答

1

的應用程序/型號目錄設置爲自動加載路徑。這意味着如果它找不到符號,它只會需要該文件。根據你的情況,因爲它是在創業板已定義的,自動加載永遠不會觸發,這就是爲什麼你沒有得到default_scope

+0

Intereting!有沒有辦法強制軌道重新加載模型? – DVG

+0

你可以做這樣的事情Dir.glob( 「#{} Rails.root /應用/模型/ * RB」)sort.each {|。文件|初始化程序中的require_dependency file} – bridiver