Skip to content

Instantly share code, notes, and snippets.

@mikeda
Last active June 28, 2018 04:40
Show Gist options
  • Save mikeda/d16f02f2b370e3349211833f02276fc3 to your computer and use it in GitHub Desktop.
Save mikeda/d16f02f2b370e3349211833f02276fc3 to your computer and use it in GitHub Desktop.
子レコードのデータは不要でexists?かどうかだけ知りたい場合のN+1対応を効率的にやる方法が知りたい
# 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