Rails按相关模型排序

Bry*_*ard 40 ruby-on-rails

我有一个has_many关系中的两个模型,以便Log has_many Items.然后,Rails很好地设置了以下内容:some_log.items将所有相关项返回给some_log.如果我想根据Items模型中的不同字段来订购这些项目,有没有办法通过类似的结构来实现,或者必须分解为:

Item.find_by_log_id(:all,some_log.id => "some_col DESC")
Run Code Online (Sandbox Code Playgroud)

Gre*_*ell 75

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

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

class Log < ActiveRecord::Base
  has_many :items, :order => "some_col DESC"
end
Run Code Online (Sandbox Code Playgroud)

您也可以使用named_scope执行此操作,这将允许在访问项时随时轻松指定顺序:

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
Run Code Online (Sandbox Code Playgroud)

如果您始终希望默认情况下以相同的方式排序项目,则可以使用(Rails 2.3中的新建)default_scope方法,如下所示:

class Item < ActiveRecord::Base
  default_scope :order => "some_col DESC"
end
Run Code Online (Sandbox Code Playgroud)

  • 在Rails 4中,还有另一种方法.默认关联范围应指定为lambda,如`has_many:items, - > {order(:some_col).where(foo:'bar')}`,类似地,命名范围现在采用lambda`范围:name_of_scope, - > {where(foo:'bar')}`.默认范围采用块:`default_scope:{where(foo:'bar')}` (13认同)
  • 从Rails 3.x开始,named_scope语法略有不同.现在使用"scope"而不是"named_scope"调用它,并使用函数来定义范围结构.例如:"范围:有序,顺序("some_col DESC")". (12认同)

lfe*_*445 16

rails 4.2.20语法需要使用块调用:

class Item < ActiveRecord::Base
  default_scope { order('some_col DESC') }
end
Run Code Online (Sandbox Code Playgroud)

这也可以使用替代语法编写:

default_scope { order(some_col: :desc) }
Run Code Online (Sandbox Code Playgroud)