繁体   English   中英

通过两个字段进行排序,其中一个正在创建中,在Rails中

[英]Ordering by a two fields, one being created_at, In Rails

这是Rails 3中定制,高效,复杂订购的后续问题

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

  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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM