ruby-on-rails – Datamapper:通过关联对结果进行排序

我正在开发一个使用Datamapper作为其ORM的Rails 3.2应用程序.我正在寻找一种通过关联模型的属性对结果集进行排序的方法.具体来说我有以下型号:
class Vehicle
  include DataMapper::Resource

  belongs_to :user
end

class User
  include DataMapper::Resource

  has n,:vehicles
end

现在我希望能够查询车辆并按驱动程序的名称对它们进行排序.我尝试了以下但似乎没有使用Datamapper:

> Vehicle.all( :order => 'users.name' )
ArgumentError: +options[:order]+ entry "users.name" does not map to a property in Vehicle

> Vehicle.all( :order => { :users => 'name' } )
ArgumentError: +options[:order]+ entry [:users,"name"] of an unsupported object Array

现在我正在使用Ruby来对查询后的结果集进行排序,但显然这对任何性能没有帮助,也阻止了我对其他范围的进一步链接.

解决方法

我花了一些时间去挖掘,最后出现了一个博客,解决了这个问题.它涉及在DataMapper中手动构建排序查询.

来自:http://rhnh.net/2010/12/01/ordering-by-a-field-in-a-join-model-with-datamapper

def self.ordered_by_vehicle_name direction = :asc
  order = DataMapper::Query::Direction.new(vehicle.name,direction)
  query = all.query
  query.instance_variable_set("@order",[order])
  query.instance_variable_set("@links",[relationships['vehicle'].inverse])
  all(query)
end

这将允许您通过关联订购并仍然链接到其他范围,例如:

User.ordered_by_vehicle_name(:desc).all( :name => 'foo' )

它有点hacky但它​​至少做了我想要它做的事情;)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...