3

我有一个模型:

class Event
    has_many :participations
    has_many :participants, :through => :participations, :source => user

    def attending?(user)
        participants.exists?(user)
    end
end

我在使用的时候注意到了一个 N+1 查询问题,比如:

@events = Event.all
@events.each_with_index do |event, i|
    if (event.attending?(current_user))
        ...
    end
end

我想我可以通过使用包含来解决这个问题:

@events = Event.includes(:participants)

这并不能解决 N+1 查询问题。我对 Ruby 不是很好(这是一个附带项目),但是在调试 的代码时ActiveRecord.FinderMethods.exists?,我相信它总是在构建一个新的关系并针对服务器执行它,无论包含什么。

我的解释exists?正确吗?如果没有,我怎样才能包含正确的东西以使exists?不显示 N+1 查询问题?

4

1 回答 1

0

作为参考,我最终通过以下方式解决了这个问题:

@events = Event.includes(:participants)

def attending?(user)
    participants.where('user_id = ?', user.id)
end
于 2013-09-19T06:28:44.597 回答