我有一个Rails API,目前有很多我想减少的N + 1查询。
您可以看到它在返回数据之前经历了很多循环。
关系如下:
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查询来自序列化程序内部时,我不确定如何处理此问题查看工具和技术。
任何帮助将不胜感激!
尝试嵌套预加载:
Job.preload(:technologies, :tools, company: :listings).order(...).where(...)
您可能非常渴望加载工具和技术,因为您知道序列化程序将使用它们:
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