我相信我有一个 N + 1 问题,但我想看看是否有人可以就如何优化这个问题提供任何建议,因为我的代码正在运行太多查询。
控制器/profit_reports_controller.rb
def weekly
@sales = Sale.by_category(@category).this_week(@beg_of_week)
@departments = Department.by_category(@category)
end
利润报告/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)}