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’.

    @artworks = Artwork.find(:all, :include => :artist, :order => “artists.last_name, title”)

Like most things in rails ordering by associations is easy once you know how.

3 Responses to “Ruby on Rails Order by Associated Model”

  1. Meekish Says:

    Hey, that’s cool. I thought ordering could only be done with SQL.

  2. Ruby on Rails Order by Associated Model « Neokain on Train Says:

    […] ที่มา: http://blog.vixiom.com/ […]

  3. Andreas Says:

    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)!

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image