Reputation: 590
I need help to write a method to sum the total number of comments a user has from all the user posts.
has_many :posts
has_many :comments
beongs_to :post
I tied this in the user's helper
def all_comments(user)
user_posts = user.posts.all
user_posts.each do |post|
return post.comments.count ++
end
end
Upvotes: 0
Views: 46
Reputation: 357
The first answer is right and will give you the right results but it will be slow if the User has a lot comments. count
will perform an SQL COUNT
query, in short it will count one by one and will perform very slow, use size
instead to avoid excessive queries.
Comment.where(post_id: @user.posts.pluck(:id)).size
Upvotes: 0
Reputation: 131
The first solution that came to my mind was as follows;
Comment.where(post_id: @user.posts.pluck(:id)).count
Upvotes: 1