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

这是Rails 3中自定义,高效,复杂排序的后续问题

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

Model.order('popularity ASC') 

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

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

那么:我怎么能这样做,它是否有效?

在计算您的受欢迎程度时,您可以只考虑创建时间;)

在你的模型中,你可以做一些……

 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