我正在开发一个使用 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 中手动构建排序查询。
From: http://rhnh.net/2010/12/01/ordering-by-a-field-in-a-join-model-with-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,但它至少做了我想要它做的事情;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)