您可以使用default_scope
此:
class Club < ActiveRecord::Base
has_many :courses, conditions => {:approved => true}
default_scope :include => :courses
end
class Course < ActiveRecord::Base
default_scope :conditions => {:approved => true}
end
現在你可以這樣做:
@club = Club.find(1) # this will eager load approved courses.
參考:
Article約default_scope
。
注1
我改變了courses
ASSOCATION在Club
類選擇認可的課程。理論上,這不是必需的,因爲Course
類具有默認範圍。但是,它看起來像默認範圍不適用於預先加載的查詢。
注2
我個人並不急於負載Course
對象通過default_scope
。通過default_scope做到這一點,可以根據您的需要爲您提供一個不顯眼的解決方案。
我會將include
子句添加到find
調用中,只有在需要時纔會加載Course
對象。
注3
@Ryan比格:
約默認範圍瑞恩·貝茨會談通過這個他screen cast一半。他給出了一個使用默認示波器排除刪除記錄的例子,即
default_scope :conditions => "delete_at IS NULL"
我認爲這個用例是類似的。當我發現問題時,課程模型的主要操作在批准的記錄上,default_scope
與conditions
選項確保。要覆蓋default_scope,用戶可以使用with_exclusive_scope
方法。
Club.with_exclusive_scope{find(1)}
您可以使用動態範圍而不是named_scope,即'@ club.courses.scoped_by_approval(true)'或'@ club.courses.scoped_by_approval(false)'。 – 2010-08-09 18:36:15
嘿,現在只是漂亮! – Jay 2010-08-10 01:29:12