foliwe83
foliwe83

Reputation: 590

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

has_many :posts

Post.rb

has_many :comments

Comment.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
     

Upvotes: 0

Views: 46

Answers (2)

Juan Artau
Juan Artau

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

Muhammet Dilmaç
Muhammet Dilmaç

Reputation: 131

The first solution that came to my mind was as follows;

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

Upvotes: 1

Related Questions