【问题标题】:How to avoid N+1 queries in Rails如何避免 Rails 中的 N+1 查询
【发布时间】:2015-10-11 08:04:19
【问题描述】:

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

  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)

有什么办法可以避免吗?

【问题讨论】:

标签: sql ruby-on-rails activerecord


【解决方案1】:

编辑

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

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

【讨论】:

  • stats.cache.id(你的代码)与 stats.cache_id(我的)不同
  • 抛出以下错误:undefined method `cache_id' for #&lt;Statistic:0x007fbb6a2c8d28&gt;
  • 我也找到了关于N+1 Problem的好文章
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多