I have two models that are associated. I have an Artist model and a Review model.
class Artist
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :reviews
end
class Review
include DataMapper::Resource
property :id, Serial
property :rating, Integer
property :body, String
belongs_to :artist
end
My goal is to retrieve an array of artists ordered by the average rating of the reviews associated with them. I’m not sure if there is any one line solution to this, but my current method is to create an array with the id’s of the artists sorted by average rating. The details of how I obtain this array is not important for this question but let’s say I now have an array.
ids_sorted_by_rating = [4,5,23,9,2,48,17,....]
I then retrieve the artists.
artists = Artist.all(:id => ids_sorted_by_rating)
The problem is that datamapper orders by :id unless you specify another option. So after all my hard work to get ids_sorted_by_rating, I’m still left with a list of artists just sorted by :id.
Any solution that gives me a list of artists ordered by the average rating of the associated reviews would be MUCH appreciated. Bonus points if I don’t need to hit the database a million times to get that list. 🙂
Thanks and if you need more info just ask and I’ll provide!
AFAIK there is no easy way to do sorting by aggregation in DataMapper (the way to go to do it in single query). You can use an app-side reordering of results (unless your datasets are too big for this):