Ordering by a two fields, one being created_at, In Rails

守給你的承諾、 提交于 2019-12-25 01:44:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!