使用包含后,N + 1查询是否仍然存在?

时间:2017-12-07 01:22:42

标签: ruby-on-rails

以下内容应使用JOINS加载一堆关联:

Event.where(id: @events.map(&:id))
     .includes(
                :user,
                :event_category,
                task: [:document_tasks, task_followers: :follower]
      ).each do |event|
        owner = event.task.task_followers.where(owner: true).first.follower
      end  

现在当我逐步浏览每个事件并使用上面检索的关联时,我不应该看到任何N + 1个查询:

D, [2017-12-06T19:46:17.536892 #26637] DEBUG -- :   TaskFollower Load (2.9ms)  
SELECT  `task_followers`.* FROM `task_followers` 
WHERE `task_followers`.`task_id` = 11635 AND `task_followers`.`owner` = 1  
ORDER BY `task_followers`.`id` ASC LIMIT 1

但是我看到了大量的问题,如下所示:

class Event < ActiveRecord::Base
    belongs_to :user
    belongs_to :task
    belongs_to :event_category
end

class Task < ActiveRecord::Base
    has_many :document_tasks, dependent: :destroy
    has_many :task_followers, dependent: :destroy
    has_many :followers, through: :task_followers, dependent: :destroy
    has_one :fullcalendar_engine_event, class_name: 'FullcalendarEngine::Event'
end

关系:

{{1}}

为什么会这样?

1 个答案:

答案 0 :(得分:1)

我认为这是由于您的来电where(owner: true)。这导致它发送另一个查询来过滤您的结果。请尝试将其替换为select(&:owner?)

# Change this line
owner = event.task.task_followers.where(owner: true).first.follower
# to this
owner = event.task.task_followers.select(&:owner?).first.follower