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

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Ariff Munshi asked in General

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.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.