Skip to content

Instantly share code, notes, and snippets.

@codertcet111
Created March 31, 2023 06:58
#Author: Shubham Mishra
# Without joins
@users = User.all
@users.each do |user|
puts "User: #{user.name}"
puts "Posts: #{user.posts.count}"
puts "Comments: #{user.comments.count}"
end
# With joins
@users = User.joins(:posts, :comments).select("users.*, count(distinct posts.id) as post_count, count(distinct comments.id) as comment_count").group("users.id")
@users.each do |user|
puts "User: #{user.name}"
puts "Posts: #{user.post_count}"
puts "Comments: #{user.comment_count}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment