24Jul/083
rails, acts_as_rateable, will_paginate and sorting
Today I added will_paginate into my application (damn, that was easy!
). Yesterday I added acts_as_rateable with a cool web2.0 css star rating system. Not that easy, but a cool feature.
And then I wanted to combine those two. I couldn't find any nice ways of doing this, but until someone tells me a better way, the following is working out for me and helps perhaps someone else out there. Even if it could be a bit nicer.
@quotes = Quote.paginate_by_sql "SELECT quotes.*, avg(ratings.rating) AS rating, count(ratings.rating) AS votes
FROM `quotes`
LEFT JOIN ratings ON quotes.id = ratings.rateable_id
WHERE (ratings.rateable_type = 'Quote' OR ratings.rateable_type IS NULL)
GROUP BY ratings.rateable_id
ORDER BY rating DESC, votes DESC",
:page => params[:page]
Edit: I fixed it, it returns now quotes without a rating too.

Juli 27th, 2008 - 17:50
Forget what I said here, it’s really inefficient… I just stumbled upon (or actually really searched for) a article, which describes an easy way to cache the rating and make searches as performant as it was before we put the rating into an extra table.
Juni 2nd, 2009 - 20:47
Thanks for taking time to post this. Your dash of magic helped me out of a pickle.
Juni 2nd, 2009 - 23:18
More than happy, that it helped someone.