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,
rder => "artists.last_name, title")
Like most things in rails ordering by associations is easy once you know how.
This entry was written by
Alastair, posted on
September 27, 2006 at 1:46 pm, filed under
Ruby on Rails. Bookmark the
permalink. Follow any comments here with the
RSS feed for this post.
or leave a trackback:
Trackback URL.
© Copyright 2006 - 2012 Alastair Dawson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
2 Comments
Hey, that’s cool. I thought ordering could only be done with SQL.
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
[...] ที่มา: http://blog.vixiom.com/ [...]