Skip to content

Instantly share code, notes, and snippets.

@mitsuru793
Last active February 16, 2016 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitsuru793/3c652890e2ff72a77f3f to your computer and use it in GitHub Desktop.
Save mitsuru793/3c652890e2ff72a77f3f to your computer and use it in GitHub Desktop.
Railsで孫レコードの数を取得する
# 分かりやすく
blog = Blog.first
article_counts = blog.categories.map { |category| category.articles.count }
article_total = article_counts_counts.sum
# joinsを使う
article_total = Blog.joins(categories: :articles).where(id: 1).count
# 別パターン
blog = Blog.first
article_total = blog.categories.joins(:articles).count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment