我一直試圖根據我的rails3應用程序中的某些範圍急切加載關聯,但是找不到任何解決方案。Eagerloading在rails3中的範圍確定
我的應用程序有以下型號:
class Project
has_many :entries
has_many :to_dos
class ToDo
has_may :entries
has_many :tasks
belongs_to :project
class Task
has_many :entries
belongs_to :to_do
class Entry
belongs_to :project
belongs_to :to_do
belongs_to :task
# options format: {:from_date=>(Date.today-1.week), :to_date=>(Date.today+1.week), :user_id=>60}
scope :filtered_list, lambda { |options|
condition = options[:user_id].nil? ? "true" : "user_id = #{options[:user_id]}"
condition += options[:from_date].nil? ? "" : " AND entry_date >= '#{options[:from_date]}'"
condition += options[:to_date].nil? ? "" : " AND entry_date <= '#{options[:to_date]}'"
where(condition)
}
並在項目中我有以下代碼#指數來獲得一個用戶的所有項目:
@projects = current_user.projects.includes(:entries, :to_dos =>[:entries, :tasks => :entries])
它獲取用戶的所有項目,沿急切地加載關聯。所以當我執行下面的循環來獲取項目中的所有條目時,沒有新的查詢被觸發。
def all_entries(options)
entries = self.entries
self.to_dos.each do |d|
entries += d.entries
d.tasks.each do |t|
entries += t.entries
end
end
end
由於這種急切的加載獲取所有條目,它比我實際需要的數據太多。所以我嘗試了一些條件來加載項目,但找不到任何解決方案。我正在尋找類似的東西:
@projects = current_user.projects.includes(:entries.filtered_list(options), :to_dos =>[:entries.filtered_list(options), :tasks => :entries.filtered_list(options)])
這樣只有符合條件的條目纔會被加載。
我們不能在急切加載時使用範圍界定嗎? 請幫助我一起使用預先確定的範圍。