Order by two fields, one of which is created_at, In Rails

This is the next question Custom, Efficient, Complex Ordering in Rails 3

I would like to develop an efficient sequencing method for the rail model I have. Suppose I keep a rating for all objects in a field named "popularity." If I wanted to sort this rating, I would do:

  Model.order('popularity ASC')

How do I order oblique for the created? Is there a way, perhaps, to convert the creation timestamp to an integer value, and then sort by popularity - created_at, so that estimates of old objects decrease over time? IE is something like:

  Model.order('popularity-integerize(created_at) ASC')

So: how can I do this, and is it effective?

0
source share
2

;)

0

- ...

class Model < ActiveRecord::Base
  def decaying_popularity
    popularity + created_at.to_i # created_at is larger for newer creations.
  end                            # you'll obviously need to edit the formula you use. 

  def self.order_by_decaying_popularity
    models = self.all
    models.sort {|a,b| a.decaying_popularity <=> b.decaying_popularity }
  end
end

:

Model.order_by_decaying_popularity

:

Model.where(:author_id => 1).order_by_decaying_popularity
0

All Articles