且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 按关联模型排序

更新时间:2023-09-28 21:43:16

有多种方法可以做到这一点:

There are multiple ways to do this:

如果您希望以这种方式对该关联的所有调用进行排序,您可以在创建关联时指定排序,如下所示:

If you want all calls to that association to be ordered that way, you can specify the ordering when you create the association, as follows:

class Log < ActiveRecord::Base
  has_many :items, :order => "some_col DESC"
end

您也可以使用 named_scope 来执行此操作,这样可以在任何时候访问 Item 时轻松指定排序:

You could also do this with a named_scope, which would allow that ordering to be easily specified any time Item is accessed:

class Item < ActiveRecord::Base
  named_scope :ordered, :order => "some_col DESC"
end

class Log < ActiveRecord::Base
  has_many :items
end

log.items # uses the default ordering
log.items.ordered # uses the "some_col DESC" ordering

如果你总是希望物品默认以相同的方式排序,你可以使用(Rails 2.3 中新增的)default_scope 方法,如下所示:

If you always want the items to be ordered in the same way by default, you can use the (new in Rails 2.3) default_scope method, as follows:

class Item < ActiveRecord::Base
  default_scope :order => "some_col DESC"
end