has_many中的N + 1:通过

时间:2018-03-13 15:22:54

标签: ruby-on-rails ruby-on-rails-5

我遇到问题N + 1 联合:

class Category < ApplicationRecord
  has_many :categories_designs, dependent: :destroy
  has_many :designs, through: :categories_designs
  has_many :templates, ->{ where(is_template: true) }, through: :categories_designs, class_name: 'Design', source: :design

  def marked_designs_as_new?
    designs.select(:mark_design_as_new_until).where("mark_design_as_new_until >= ?", Time.now.in_time_zone.beginning_of_day).exists?
  end
end

我想在视图中使用marked_designs_as_new?方法。

- @categories.each do |category|
  = category.title.titleize
  - if category.marked_designs_as_new?
    .design-type-marked
      NEW

在我的控制器中,我打电话:

@categories = Category.includes(categories_designs: :design).visible

我遇到了N + 1的问题。

Category Load (0.4ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."hidden" = $1 ORDER BY "categories"."position" ASC LIMIT $2 OFFSET $3  [["hidden", false], ["LIMIT", 100], ["OFFSET", 0]]
  CategoriesDesign Load (0.4ms)  SELECT "categories_designs".* FROM "categories_designs" WHERE "categories_designs"."category_id" IN (1, 3, 4, 5, 6, 7, 8)
  Design Load (0.5ms)  SELECT "designs".* FROM "designs" WHERE "designs"."id" IN (1, 4, 3, 6)
   (0.7ms)  SELECT COUNT(*) FROM "designs" INNER JOIN "categories_designs" ON "designs"."id" = "categories_designs"."design_id" WHERE "categories_designs"."category_id" = $1 AND "designs"."is_template" = $2  [["category_id", 1], ["is_template", true]]
  Design Exists (0.7ms)  SELECT  1 AS one FROM "designs" INNER JOIN "categories_designs" ON "designs"."id" = "categories_designs"."design_id" WHERE "categories_designs"."category_id" = $1 AND (mark_design_as_new_until >= '2018-03-13 00:00:00') LIMIT $2  [["category_id", 1], ["LIMIT", 1]]
   (0.5ms)  SELECT COUNT(*) FROM "designs" INNER JOIN "categories_designs" ON "designs"."id" = "categories_designs"."design_id" WHERE "categories_designs"."category_id" = $1 AND "designs"."is_template" = $2  [["category_id", 3], ["is_template", true]]
............. etc.

为什么?

2 个答案:

答案 0 :(得分:0)

好的,您的.select(:mark_design_as_new_until)会对数据库执行另一次查询。您应该采用以下方式使用数组选择方法:

.select(&:mark_design_as_new_until)

这为您提供了一系列加载在内存中的设计,您可以在其中执行.any?方法来检查您的状况:

.select(&:mark_design_as_new_until).any? { |design| design.mark_design_as_new_until >= Time.now.in_time_zone.beginning_of_day }

当然,请在您的类别中添加designs

Category.includes(:designs, ...)

答案 1 :(得分:0)

您是否尝试Category.includes([:categories_designs, :design])此外,您可以按如下方式更改marked_designs_as_new?方法,

def marked_designs_as_new?
  designs.select{ |x| x.marked_designs_as_new? }.any?
end

design.rb

class Design
  def marked_designs_as_new?
    mark_design_as_new_until >= Time.now.in_time_zone.beginning_of_day
  end
end