Sorting Collections of Model Data

In Rails, it happens from time to time that you have an array of instances of some class, and you want to re-sort them based on a specific attribute.

For example, maybe you have an array of hockey games. Each Game instance has the following attributes:

  • Home Team (integer)
  • Visiting Team (integer)
  • Game Time (date and time)
  • Location (string)

By default, Rails will sort your array by id; so if you use games = Game.find_all(), you’ll get all the games, in the order your database has the IDs.

But what if you want to sort by, for example, location, so players can find which games are closest to them? Rails provides a sort_by function. With some sugar-coated syntax, you can code the sort in one line:

by_location = games.sort_by(&:location)

You can then access the array by_location, and it’ll contain all the games, sorted by location.

Depending on your application, if you have, for example, an association between games and players–a many-to-many relation–then you might code something like this:


class Player
has_many :games
# ...
end

Even better, you can sort associations in a many-to-one or many-to-many relationship. Simply specify the :order attribute in the has_many side of the relation, and specify the attribute to sort by. Not only can you sort by one attribute, you can even have multiple collections of the same data, sorted differently! Observe:


class Player
has_many :games_by_location, :class_name => "Game", :order => location
has_many :next_five_games, :class_name => "Game", :order => game_time
# ...
end

(You need to specify the :class_name key because the collection names aren’t “games”, as Rails expects.) Simply access the collections as some_player.games_by_location or some_player.next_five_games to grab the data. This powerful feature gives you the ability to slice and dice your data however you want.

In conclusion: Rails provides a powerful and flexible sorting mechanism that makes it easy to sort collections, and also to maintain different “views” of the same collection, sorted differently.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , . Bookmark the permalink.

Comments are closed.