$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
dabbling, frivolling, idling, loafing, loitering, playing and procrastinating
6 Jan // php the_time('Y') ?>
An odd titled name for something that I had to remember how to do today. If you need to sort something by the number of its has_many object, eg…
Album has_many photos, listing albums with the most photos first
Forum has_many posts, listing forums with the most posts first
Group has_many users, listing groups with the most users first
…and you want to show these parents ordered by the number of children objects they have you need to do this…
a = Album.find(:all).sort { |x,y| x.photos.size <=> y.photos.size }
Obviously you can use named_scopes and conditions to restrict it down if you don’t want all of a certain object, either child or parent.
Hopefully this helps someone out.
One Response for "Rails: Sorting a model by has_many associations"
How would a named_scope work in this example?
I have a Student model that has_many :attendances.
My Attendance model has a “date” attribute – the various days the student attended class.
How would I sort my Students list so the student who has attended class most recently are at the top? In other words with the most recent attendances.date? How would I do this in a named_scope? Thanks – nice site.
Chris
Leave a reply