问题
This is a follow-up question to Custom, Efficient, Complex Ordering in Rails 3
I'd like to develop an efficient ordering method for a rails model I have. Suppose that I save a rating for all objects in a field named "popularity". If I wanted to sort by this rating I would do:
Model.order('popularity ASC')
How would I order by a skew for created at? Is there a way to, perhaps, convert the creation timestamp to an integer value, and then sort by popularity - created_at such that older objects' ratings decrease over time? IE something like:
Model.order('popularity-integerize(created_at) ASC')
So: how might I do this, and is it efficient?
回答1:
When calculating your popularity, you could just keep the creation time into consideration ;)
回答2:
In your model, you could do something along the lines of...
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
When you want to call it in your controller:
Model.order_by_decaying_popularity
It should play nice with other clauses, too:
Model.where(:author_id => 1).order_by_decaying_popularity
来源:https://stackoverflow.com/questions/8728287/ordering-by-a-two-fields-one-being-created-at-in-rails