我需要帮助编写一个方法来计算用户从所有用户帖子中获得的评论总数。
user.rb
has_many :posts
Post.rb
has_many :comments
Comment.rb
beongs_to :post
我在用户的助手中绑定了这个
def all_comments(user)
user_posts = user.posts.all
user_posts.each do |post|
return post.comments.count ++
end
end
我想到的第一个解决方案如下;
Comment.where(post_id: @user.posts.pluck(:id)).count
第一个答案是正确的,会给你正确的结果,但如果用户有很多评论,它会很慢。count
将执行SQLCOUNT
查询,简而言之,它将逐个计数,并且执行速度非常慢,请改用size
以避免过多的查询。
Comment.where(post_id: @user.posts.pluck(:id)).size