我正在开发一个使用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
解决方法
我花了一些时间去挖掘,最后出现了一个老博客,解决了这个问题.它涉及在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但它至少做了我想要它做的事情;)