0

I was reading this Stack Overflow question and was wondering what is a common practice to store popularity values for data in a Ruby on Rails application?

My thinking is to have 2 models, a regular model and a popular one that has data from the regular model sorted by a popularity formula. A cronjob would populate the latter model at some specific interval.

Any thoughts?

Community
  • 1
  • 1
Raisen
  • 4,385
  • 2
  • 25
  • 40

4 Answers4

0

It would depend on the specifics, but I think you can store the popularity information as a column in the model. For example, if you had Questions which you wanted to sort by popularity, you could run a migration AddPopularityToQuestions popularity:float.

You could then run a script at set intervals (e.g. with Whenever) to update the popularity value for each question. However, if there isn't that much activity, it might make more sense to update the popularity for a question whenever something happens that will change it. For example, if popularity is mainly determined by votes, you could update a question's popularity whenever there are new votes.

Ari
  • 1,974
  • 19
  • 30
0

Use one rake task to update the popularity and run it with heroku scheduler.

Thaha kp
  • 3,689
  • 1
  • 26
  • 25
0

I would imagine popularity to be statistical. For example, views over the last 7 days, etc. The measurement you might want to use might change, even allowing the user to select which formula to use.

In this case, you'd want a Statistics model that belongs_to the regular model, and you can join the tables to get the popularity measurement that you're interested in.

aceofspades
  • 7,568
  • 1
  • 35
  • 48
0

I would go with a popularity_score field in the model and a scope that returns the popular items for example:

def popular(count = 10)
  order('popularity_score DESC').limit(count)
end

depending on the scoring algorithm, I may add additional model to hold the statistics

class model_stats
  attr_accessor :statistic, :value
  belongs_to :model
end

This could hold stats like views, up_votes or shares which would be periodically aggregated using your preferred popularity algorithm and the result saved into popularity_score. (managed as a rake task kicked off by cron or similar)

I would make sure that popularity_score was an indexed field!

Ian Kenney
  • 6,376
  • 1
  • 25
  • 44