Ruby on Rails Order by Associated Model
Grouping information helps users traverse your app in a much faster manner (and thus be more productive which leads them to rave about your mad skills to their friends and refer you more work!). Today I was building a website for a gallery and needed to show the list of artwork entered into the system. At first I was ordering the artwork by ‘artist_id’ and ‘title’ but since ‘Artists’ aren’t necessarily going to be entered in alphabetical order the list doesn’t make sense ordered by ‘artist_id’ (sense to a human expecting alphabetical ordering).
After a couple of failed attempts I remembered the ‘:include’ argument for the ‘find’ method. Once I included artists into the artwork result I could order by ‘artist.last_name’.
Like most things in rails ordering by associations is easy once you know how.




Like this post? subscribe to the feed.






Hey, that’s cool. I thought ordering could only be done with SQL.
Comment by Meekish — September 27, 2006 @ 9:10 pm
[…] ที่มา: http://blog.vixiom.com/ […]
Pingback by Ruby on Rails Order by Associated Model « Neokain on Train — February 22, 2007 @ 2:56 am
Thanks a bunch! I’ve totally missed the necessity of “:include”. I was trying for hours to sort directly via an associated table entry without any luck. You really saved my day (night)!
Comment by Andreas — June 12, 2007 @ 2:35 pm