简体   繁体   English

在 Rails 中编写辅助方法

[英]Writing helper method in rails

I need help to write a method to sum the total number of comments a user has from all the user posts.我需要帮助来编写一种方法来汇总用户从所有用户帖子中获得的评论总数。

user.rb用户.rb

has_many :posts

Post.rb Post.rb

has_many :comments

Comment.rb评论.rb

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
     

The first solution that came to my mind was as follows;我想到的第一个解决方案如下;

Comment.where(post_id: @user.posts.pluck(:id)).count

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. count将执行 SQL COUNT查询,简而言之它会一个一个地计数并且执行速度很慢,使用size代替以避免过多的查询。

Comment.where(post_id: @user.posts.pluck(:id)).size

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM