Datamapper: Sorting results through association

半腔热情 提交于 2019-12-04 06:07:20

I spent some more time digging around and finally turned up an old blog which has a solution to this problem. It involves manually building the ordering query in DataMapper.

From: 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

This will let you order by association and still chain on other scopes, e.g.:

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

It's a bit hacky but it does what I wanted it to do at least ;)

Note: I'm not familiar with DataMapper and my answer might not be within the standards and recommendations of using DataMapper, but it should hopefully give you the result you're looking for.


I've been looking through various Google searches and the DataMapper documentation and I haven't found a way to "order by assocation attribute". The only solution I have thought of is "raw" SQL.

The query would look like this.

SELECT vehicles.* FROM vehicles
LEFT JOIN users ON vehicles.user_id = users.id
ORDER BY users.name

Unfortunately, from my understanding, when you directly query the database you won't get the Vehicle object, but the data from the database.

From the documentation: http://datamapper.org/docs/find.html. It's near the bottom titled "Talking directly to your data-store"

Note that this will not return Zoo objects, rather the raw data straight from the database

Vehicle.joins(:user).order('users.name').all

or in Rails 2.3,

Vehicle.all(:joins => "inner join users on vehicles.user_id = user.id", :order => 'users.name')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!