我有一个模型与这两种方法project_lead
和project_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
这是我的包含声明:
Project.includes(:customer, project_contributions: [ :employee ]).all
但是我仍然得到n + 1个查询.
有什么办法可以减少查询次数吗?
该where
子句作用于一个ActiveRecord
对象.project_contributions
是的,Enumerable
所以你可以在它上面做迭代方法map
,select
等等.不需要再次查询表来获得你想要的东西.
顺便说一下为什么不在joins
这里使用呢?你可以用joins
而不是include
.由于includes
您customer
没有使用该Customer
模型的属性,因此您急切地加载了在您的案例中过度杀伤的模型.只是我的两分钱.
Project.joins(:customer, project_contributions: [ :employee ]).all