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,  :o rder => "artists.last_name, title")

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

This entry was posted in Ruby on Rails. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Meekish
    Posted September 27, 2006 at 9:10 pm | Permalink

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

  2. Andreas
    Posted June 12, 2007 at 2:35 pm | Permalink

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

One Trackback

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

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word