Last active
June 28, 2018 04:40
-
-
Save mikeda/d16f02f2b370e3349211833f02276fc3 to your computer and use it in GitHub Desktop.
子レコードのデータは不要でexists?かどうかだけ知りたい場合のN+1対応を効率的にやる方法が知りたい
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Articleがhas_many :commentsな時に、 | |
# Articleの一覧といっしょに、それぞれにcommentsが存在するかどうかの情報がほしい | |
# これだとN+1になる | |
articles = Article.all | |
articles.each do |article| | |
commented = article.comments.exists? | |
end | |
# N+1にはならないけど不要なcommentsが全てロードされてなんかムダっぽい | |
articles = Article.includes(:comments) | |
articles.each do |article| | |
commented = article.comments.present? | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment