移除印象派宝石的N + 1条查询

时间:2018-12-02 21:30:02

标签: ruby-on-rails ruby impressionist

在我的Rails应用程序中,我遇到了N + 1问题,我要对数据库进行额外的调用以一次又一次地获取关联的数据,尤其是在记录每个模型的印象时。

例如:

Started GET "/" for 127.0.0.1 at 2018-12-02 16:21:05 -0500
Processing by JobsController#index as HTML
  Job Load (4.4ms)  SELECT  "jobs".* FROM "jobs" WHERE "jobs"."published_at" IS NOT NULL ORDER BY "jobs"."published_at" DESC LIMIT $1 OFFSET $2  [["LIMIT", 30], ["OFFSET", 0]]
  ↳ app/controllers/jobs_controller.rb:22
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/controllers/jobs_controller.rb:24
  Impression Exists (1.3ms)  SELECT  1 AS one FROM "impressions" WHERE "impressions"."impressionable_id" = $1 AND "impressions"."impressionable_type" = $2 AND "impressions"."session_hash" = $3 LIMIT $4  [["impressionable_id", 705], ["impressionable_type", "Job"], ["session_hash", "d80d52dd401011a626d600167140e49f"], ["LIMIT", 1]]
  ↳ app/controllers/jobs_controller.rb:24
  Impression Exists (0.6ms)  SELECT  1 AS one FROM "impressions" WHERE "impressions"."impressionable_id" = $1 AND "impressions"."impressionable_type" = $2 AND "impressions"."session_hash" = $3 LIMIT $4  [["impressionable_id", 704], ["impressionable_type", "Job"], ["session_hash", "d80d52dd401011a626d600167140e49f"], ["LIMIT", 1]]
  ↳ app/controllers/jobs_controller.rb:24
  Impression Exists (0.4ms)  SELECT  1 AS one FROM "impressions" WHERE "impressions"."impressionable_id" = $1 AND "impressions"."impressionable_type" = $2 AND "impressions"."session_hash" = $3 LIMIT $4  [["impressionable_id", 703], ["impressionable_type", "Job"], ["session_hash", "d80d52dd401011a626d600167140e49f"], ["LIMIT", 1]]
  ↳ app/controllers/jobs_controller.rb:24

我正在使用impressionist gem和直接使用impressionist方法,获取页面上的所有Jobs并记录一次印象。问题是因为我只记录唯一的印象,对于已经有impression的记录,这些额外的调用是多余的。我尝试使用@jobs.includes(:impressions).each来预加载关联的数据,希望Rails足够聪明以找出存在哪些记录,但是Rails仍然会输出许多Impression Exists查询。

@jobs.each{|job| impressionist(job,'', :unique => [:session_hash])}

0 个答案:

没有答案