如何避免Rails中的N + 1查询

时间:2015-10-11 08:04:19

标签: sql ruby-on-rails activerecord

我在控制器中有以下请求:

  def show
    @statistics = Keyword.find(params[:id]).statistics.order(:word).paginate :per_page => 10, :page => params[:page]
  end

在视图文件的一个位置,我请求一个缓存id参数:

<td><%= link_to "Open", cache_path(stats.cache.id), :target => "_blank"  %></td> 

生成N + 1个查询,如下所示:

 Parameters: {"id"=>"1"}
  Keyword Load (0.5ms)  SELECT  "keywords".* FROM "keywords" WHERE "keywords"."id" = $1 LIMIT 1  [["id", 1]]
   (0.4ms)  SELECT COUNT(*) FROM "statistics" WHERE "statistics"."keyword_id" = $1  [["keyword_id", 1]]
  Statistic Load (0.4ms)  SELECT  "statistics".* FROM "statistics" WHERE "statistics"."keyword_id" = $1  ORDER BY "statistics"."word" ASC LIMIT 10 OFFSET 0  [["keyword_id", 1]]
  Cache Load (0.5ms)  SELECT  "caches".* FROM "caches" WHERE "caches"."statistic_id" = $1 LIMIT 1  [["statistic_id", 5]]
  Cache Load (0.6ms)  SELECT  "caches".* FROM "caches" WHERE "caches"."statistic_id" = $1 LIMIT 1  [["statistic_id", 4]]
  Cache Load (0.5ms)  SELECT  "caches".* FROM "caches" WHERE "caches"."statistic_id" = $1 LIMIT 1  [["statistic_id", 3]]
  Cache Load (0.7ms)  SELECT  "caches".* FROM "caches" WHERE "caches"."statistic_id" = $1 LIMIT 1  [["statistic_id", 2]]
  Cache Load (0.5ms)  SELECT  "caches".* FROM "caches" WHERE "caches"."statistic_id" = $1 LIMIT 1  [["statistic_id", 1]]
  Rendered statistics/show.html.erb within layouts/application (13.7ms)

有什么办法可以避免吗?

1 个答案:

答案 0 :(得分:0)

修改

ActiveRecord有一个名为includes的方法,它确保指定的所有关联数据都以最少的查询数加载。

def show
  @keyword = Keyword.find(params[:id])
  @statistics = @keyword.statistics.includes(:cache).order("statistics.word").paginate :per_page => 10, :page => params[:page]
end