Pregunta

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.

¿Fue útil?

Solución

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')
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top