Forum: Ruby on Rails sorting a has_many collection

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
bingo b. (Guest)
on 2009-02-09 12:15
Can't quite figure this one,

I have a School (has_many reviews) and a Review (belongs_to school).

I'm rendering my reviews per school like this "@School.reviews"

Which renders the "_review.html.erb" multiple times for reviews of that
school (works a treat).

But how do I control the order in which these are displayed (I'd like to
reverse them basically most recent on top).

bb.
MaD (Guest)
on 2009-02-09 12:46
(Received via mailing list)
this should work:
@school.reviews.sort_by { |cc| - cc.updated_at.to_i }
Juan José Vidal (Guest)
on 2009-02-09 12:56
(Received via mailing list)
class School < AR
  has_many :reviews, :order => 'created_at DESC'
end

class Review < AR
  belongs_to :school
end

If you use @school.reviews you'll get the desired effect....

MaD
escribió:> this should work:
bingo b. (Guest)
on 2009-02-09 13:11
That's ideal! thanks.

Follow up question, what if I want to override this order from time to
time, say on some occasions have the reviews sorted by their last_name
column?
Juan José Vidal (Guest)
on 2009-02-09 13:19
(Received via mailing list)
You could use named_scope to get more complexity. I think that's a
possibility.

http://www.locomotivation.com/blog/2008/08/25/simp...

bingo bob escribió:
stretch (Guest)
on 2009-02-09 19:02
(Received via mailing list)
Bob,

You could also render it with jquery or some javascript library that
enables you to write the set of reviews once to javascript and present
and re-present in multiple ways as needed without more roundtrips to
the server.

Al
This topic is locked and can not be replied to.