简体   繁体   中英

How to avoid N+1 queries in Rails

I have the following request in controller:

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

And in one place of a view file I request a cache id parameter:

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

Which produces N+1 queries like the following:

 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)

Is there any way to avoid it?

EDIT

ActiveRecord has a method called includes, which ensures that all the associated datas specified are loaded with the minimum number of queries.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM