优化ActiveRecord查询属性与where

Ole*_*røm -1 sql performance activerecord ruby-on-rails

我有一个模型与这两种方法project_leadproject_operative_lead.

当我尝试获取这两个属性时,我得到了大量的查询.即使我正在尝试使用包含.

这是我的模型:

class Project < ActiveRecord::Base
  has_many :project_sales_contributions, dependent: :destroy
  has_many :sales_contributors, through: :project_sales_contributions, source: 'employee'

  has_many :project_contributions,  dependent: :destroy
  has_many :contributors, through: :project_contributions, source: 'employee'

  accepts_nested_attributes_for :project_customer_contacts,
    :project_contributions,
    :project_sales_contributions,
    allow_destroy: true,
    reject_if: :all_blank

  def project_lead
    project_contributions.where(role: 'lead').map { |e| e.employee.name }
  end

  def project_operative_lead
    project_contributions.where(role: 'operative_lead').map { |e| e.employee.name }
  end

end
Run Code Online (Sandbox Code Playgroud)

这是我的包含声明: Project.includes(:customer, project_contributions: [ :employee ]).all

但是我仍然得到n + 1个查询.

有什么办法可以减少查询次数吗?

mha*_*eeb 6

where子句作用于一个ActiveRecord对象.project_contributions是的,Enumerable所以你可以在它上面做迭代方法map,select等等.不需要再次查询表来获得你想要的东西.

顺便说一下为什么不在joins这里使用呢?你可以用joins而不是include.由于includescustomer没有使用该Customer模型的属性,因此您急切地加载了在您的案例中过度杀伤的模型.只是我的两分钱.

Project.joins(:customer, project_contributions: [ :employee ]).all
Run Code Online (Sandbox Code Playgroud)