Skip to main content

Using scopes to rank users based on votes they get from their posts

General • Asked by Ariff Munshi

Hi all, I posted this question on Stack Overflow for a problem I am stuck at.

http://stackoverflow.com/questions/30805987/using-scopes-to-order-users-with-most-votes-for-specific-time-periods

I have User model that has_many Posts that has_many Votes. I have figured how to rank users by the total number of votes they have received using scopes and the counter_culture gem to sort the total_votes_count.

The problem here is now I would like to rank them based on time periods like today, this week, this month. For this I have to total only the votes casted within those time periods. I can write scopes for the votes for these time periods like for example:
Bumps.where('created_at > ?' 1.week.ago).count

How do I pass this to total for all the post then for every user and to sort them eventually?

Any help would be great. If it really is a tough one, I'd consider to just putting the time filter on posts created_at and rank based and the total votes then order the users based on that. Need to figure out how to do that as well.

Cheers!


If you need to calculate the counts dynamically all the time, you won't be able to rely on a cache like this I don't think. You'll need to be recalculating the count as needed instead which means you'll have to store all the votes and when they happened so you can query those. It might be easiest to create an hourly cron job to update the user's votes for the day, week, month, etc.

Does that make sense?


Ok got it Chris. Time to look into writing cron jobs then! Thanks.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.