Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何优化和检查N+;Rails中的1db查询?_Ruby On Rails_Postgresql - Fatal编程技术网

Ruby on rails 如何优化和检查N+;Rails中的1db查询?

Ruby on rails 如何优化和检查N+;Rails中的1db查询?,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,我相信我有一个N+1的问题,但我想看看是否有人能就如何优化这个问题给出任何建议,因为我的代码运行的查询太多了 控制器/利润报告\u controller.rb def weekly @sales = Sale.by_category(@category).this_week(@beg_of_week) @departments = Department.by_category(@category) end <% @departments.each do |department| %

我相信我有一个N+1的问题,但我想看看是否有人能就如何优化这个问题给出任何建议,因为我的代码运行的查询太多了

控制器/利润报告\u controller.rb

def weekly
 @sales = Sale.by_category(@category).this_week(@beg_of_week)
 @departments = Department.by_category(@category)
end 
<% @departments.each do |department| %>
  <% @stores.each do |store| %>
    <% @sale = @sales.by_store(store).by_department(department).sum(:amount) %>
#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)}
利润报告/weekly.html.erb

def weekly
 @sales = Sale.by_category(@category).this_week(@beg_of_week)
 @departments = Department.by_category(@category)
end 
<% @departments.each do |department| %>
  <% @stores.each do |store| %>
    <% @sale = @sales.by_store(store).by_department(department).sum(:amount) %>
#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)}

我强烈建议使用gem。回购协议:

Bullet gem旨在帮助您提高应用程序的性能 通过减少查询数量来提高性能。它会看的 您在开发应用程序时的查询,并在 在使用eager时,应该添加eager加载(N+1个查询) 加载不必要的数据,以及何时应该使用计数器缓存


它还将告诉您如何修复它。玩得开心

您的模型之间的关系是什么?在您的代码中向我们展示。查询优化器(无论您使用的是什么RDBMS)会告诉您什么?如果我非常笼统,我很抱歉。我刚刚用销售模式更新了代码。我还没有运行任何查询优化器,但我第一次寻找建议。谢谢你的帮助,这是我的下一步!谢谢