如何删除N + 1个查询

问题描述 投票:0回答:2

我有一个Rails API,目前有很多我想减少的N + 1查询。

enter image description here

您可以看到它在返回数据之前经历了很多循环。

关系如下:

公司型号

class Company < ApplicationRecord
  has_many :jobs, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :listings
end

工作模型

class Job < ApplicationRecord
  belongs_to :company
  has_many :listings
  has_and_belongs_to_many :technologies
  has_and_belongs_to_many :tools

  scope :category, -> ( category ) { where category: category }
end

列表模式

class Listing < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :company, dependent: :destroy

  scope :is_active, -> ( active ) { where is_active: active }
end

作业序列化器

class SimpleJobSerializer < ActiveModel::Serializer
  attributes  :id,
              :title, 
              :company_name,                  

  attribute :technology_list, if: :technologies_exist
  attribute :tool_list, if: :tools_exist

  def technology_list
    custom_technologies = []

    object.technologies.each do |technology|
      custom_technology = { label: technology.label, icon: technology.icon }
      custom_technologies.push(custom_technology)
    end

    return custom_technologies
  end

  def tool_list
    custom_tools = []

    object.tools.each do |tool|
      custom_tool = { label: tool.label, icon: tool.icon }
      custom_tools.push(custom_tool)
    end

    return custom_tools    
  end

  def tools_exist
    return object.tools.any?
  end

  def technologies_exist
    return object.technologies.any?
  end

  def company_name
    object.company.name
  end
end

控制器中的当前查询

Job.eager_load(:listings).order("listings.live_date DESC").where(category: "developer", listings: { is_active: true }).first(90)

我曾尝试使用eager_load将列表添加到作业中,以使请求更有效,但是当某些n + 1查询来自序列化程序内部时,我不确定如何处理此问题查看工具和技术。

任何帮助将不胜感激!

ruby-on-rails ruby activerecord rails-activerecord active-model-serializers
2个回答
0
投票

尝试嵌套预加载:

Job.preload(:technologies, :tools, company: :listings).order(...).where(...)

0
投票

您可能非常渴望加载工具和技术,因为您知道序列化程序将使用它们:

Job.eager_load(:listings, :tools, :technologies)
   .order("listings.live_date DESC")
   .where(category: "developer", listings: { is_active: true })
   .first(90)

之后,您确实需要重构该序列化器。仅当您仅对迭代的副作用而不是返回值感兴趣时,才应使用#each。使用#map#each_with_object#inject等。可以优化这些调用。 return在红宝石中是隐式的,因此只有在提早保释时才显式返回。

class SimpleJobSerializer < ActiveModel::Serializer
  # ...
  def tool_list
    object.tools.map { |t| { label: tool.label, icon: tool.icon } }
  end
  # ...
end
© www.soinside.com 2019 - 2024. All rights reserved.