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.
September 27th, 2006 at 9:10 pm
Hey, that’s cool. I thought ordering could only be done with SQL.
February 22nd, 2007 at 2:56 am
[…] ที่มา: http://blog.vixiom.com/ […]
June 12th, 2007 at 2:35 pm
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)!