user2759575
user2759575

Reputation: 553

Rank posts by comments added today

I have two models: posts and comments. I want to rank the posts by the # of comments added today. So far I only have it ranked by the number of comments and am not sure how to add the today part.

Here is the posts controller:

@posts = Post.order('posts.comments_count desc')

I have tried

@posts = Post.order('posts.comments_count desc').where("created_at >= ?", Time.zone.now.beginning_of_day)      

but that returned nothing.

Upvotes: 2

Views: 90

Answers (1)

Joe Kennedy
Joe Kennedy

Reputation: 9443

Your second query is giving you the number of posts that have been created today, rather than the number of comments that have been created today.

This should be what you're looking for:

@posts = Post.select('posts.*, count(comments.id) as count_comments')
             .joins(:comments)
             .where('comments.created_at >= ?', Time.zone.now.beginning_of_day)
             .group('posts.id')
             .order('count_comments desc')

If you'd like to include all posts, including ones that don't have any comments today, then you'll need a left join:

@posts = Post.select('posts.*, count(comments.id) as count_comments')
             .joins("left join comments on comments.post_id = posts.id and comments.created_at >= '#{Time.zone.now.beginning_of_day}'")
             .group('posts.id')
             .order('count_comments desc')

Upvotes: 3

Related Questions