本文介绍了Rails 按关联模型排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 has_many 关系中有两个模型,以便记录 has_many 项目.Rails 然后很好地设置了类似的东西: some_log.items 它将所有关联的项目返回到 some_log.如果我想根据 Items 模型中的不同字段对这些项目进行排序,是否有一种方法可以通过类似的构造来完成此操作,或者是否必须分解为以下内容:

I have two models in a has_many relationship such that Log has_many Items. Rails then nicely sets up things like: some_log.items which returns all of the associated items to some_log. If I wanted to order these items based on a different field in the Items model is there a way to do this through a similar construct, or does one have to break down into something like:

Item.find_by_log_id(:all,some_log.id => "some_col DESC")

推荐答案

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

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

这篇关于Rails 按关联模型排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:48