-2
我相信我有一個N + 1的問題,但我想看看是否有人可以就如何優化這個問題提出任何建議,因爲我的代碼運行的方式太多的查詢。如何優化和檢查Rails中的N + 1數據庫查詢?
控制器/ profit_reports_controller.rb
def weekly
@sales = Sale.by_category(@category).this_week(@beg_of_week)
@departments = Department.by_category(@category)
end
profit_reports/weekly.html.erb
<% @departments.each do |department| %>
<% @stores.each do |store| %>
<% @sale = @sales.by_store(store).by_department(department).sum(:amount) %>
模型/ sale.rb
#Associations
belongs_to :store
belongs_to :department
#Scopes
scope :by_category, lambda {|category| where(:category_id => category.id)}
scope :by_department, lambda {|department| where(:department_id => department.id)}
scope :by_store, lambda {|store| where(:store_id => store.id)}
scope :this_week, lambda {|beg_of_week| where(:date_of_sale => beg_of_week..beg_of_week + 6.days)}
你的模型之間有什麼關係?在你的代碼中顯示我們。 – Noz
查詢優化器(您使用的任何RDBMS)會告訴您什麼? – 2013-02-04 18:45:54
如果我很一般,我很抱歉。我只是用銷售模式更新了代碼。我還沒有運行任何查詢優化器,但我第一次尋找建議。感謝你的幫助。 –