문제

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.

도움이 되었습니까?

해결책

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')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top