【发布时间】:2015-12-29 03:44:45
【问题描述】:
我有一个具有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 个查询。
有什么办法可以减少查询次数?
【问题讨论】:
-
嘿你可以用你的方法
project_contributions.includes(:employee).where(role: 'lead').map { |e| e.employee.name }实际上在你的地图是N+1查询
标签: sql ruby-on-rails performance activerecord