Vixiom Axioms

September 27, 2006

Ruby on Rails Order by Associated Model

Filed under: Ruby on Rails Alastair @ 1:46 pm

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.

Digg! submit Ruby on Rails Order by Associated Model to stumbleupon.com submit Ruby on Rails Order by Associated Model to del.icio.us submit Ruby on Rails Order by Associated Model to reddit.com Like this post? subscribe to the feed.

3 Comments »

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

    Comment by Meekish — September 27, 2006 @ 9:10 pm

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

    Pingback by Ruby on Rails Order by Associated Model « Neokain on Train — February 22, 2007 @ 2:56 am

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

RSS feed for comments on this post. TrackBack URL

Leave a comment

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

Powered by WordPress