按两个字段排序,一个是created_at,在Rails中

时间:2012-01-04 14:15:38

标签: sql ruby-on-rails ruby-on-rails-3 sorting

这是Custom, Efficient, Complex Ordering in Rails 3

的后续问题

我想开发一种有效的轨道模型订购方法。假设我为名为“popular”的字段中的所有对象保存了评级。如果我想按此评级排序,我会这样做:

  Model.order('popularity ASC')

我如何通过创建时的偏斜来命令?是否有办法将创建时间戳转换为整数值,然后按人气排序 - created_at,以便旧对象的评级随着时间的推移而降低? IE之类的东西:

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

那么:我怎么能这样做,效率很高?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在计算人气时,您可以考虑创建时间;)