簡體   English   中英

使用存在時Rails N + 1查詢? 在ActiveRelation上

[英]Rails N+1 query when using exists? on an ActiveRelation

我有一個模型:

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?的代碼時ActiveRecord.FinderMethods.exists? ,我相信它總是構建一個新的關系,並在服務器上執行它,無論包括什么。

我對exists?解釋是exists? 正確? 如果沒有,我怎樣才能包含正確的東西exists? 沒有出現N + 1查詢問題?

作為參考,我最終通過以下方式解決了這個問題:

@events = Event.includes(:participants)

def attending?(user)
    participants.where('user_id = ?', user.id)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM