Chovy’s Blog

Sorting and Ordering in Rails

Tue, April 8, 2008 — Category: Ruby on Rails

Three examples of how to sort and order things using Ruby on Rails.

Example 1: Writing your own sort routine

I originally tried ’sort_by’, but that only works for existing attributes and apparently in only one direction.

My ‘is_default’ attribute is setup as a boolean and is almost always false, except where I define an image as being the default for a given product.

Converting a boolean to a string and then sorting alphabetically in reverse order is not something I liked nor recommend, but it was the first thing that I got working.

The Admin helper:

module AdminHelper
  def sort_my_pictures(pics)
    pics.sort {|a,b| b.is_default.to_s <=> a.is_default.to_s }
  end
end

The view:

<% sort_my_pictures(product.pictures).each do |pic| %>
  <%= pic.title %>
<% end %>

Example 2: Define your own sort method available from the object instance

Defining a method on the model itself is was an improvement over Ex. 1, but still rather cumbersome to have to call it everywhere to get the sorted list of pictures. Definitely starts to break the DRY principle.

I like this method as an alternative because it can be a convenient way to override default sorting as defined in Ex. 3.

The Picture model:

class Picture < ActiveRecord::Base
	def self.sorted_another_way
	  find(:all, :order => ‘created_at DESC, title DESC, filename ASC’)
	end
end

The view:

<% product.pictures.sorted_another_way.each do |pic| %>
  <%= pic.title %>
<% end %>

Example 3 (best): Define the ordering when declaring the relationship

I was positive there was a one-liner to do what I wanted, but could not figure out how to word my question or search to reflect what I needed.

FYI: “How do I define the order when declaring a has_many relationship between models with Rails?” would have worked well. Hindsight is 20/20.

The convenience of MVC is starting to come to light!

The Product model:

class Product < ActiveRecord::Base
	#the clear winner
	has_many :pictures, :order => ‘is_default DESC, title’
end

The view:

<% product.pictures.each do |pic| %>
  <%= pic.title %>
<% end %>
  • Post Sorting and Ordering in Rails to del.icio.us
  • Post Sorting and Ordering in Rails to digg
  • Post Sorting and Ordering in Rails to Furl
  • Add Sorting and Ordering in Rails to YahooMyWeb
  • Simpify!
  • Post Sorting and Ordering in Rails to shadows
  • Post Sorting and Ordering in Rails to Spurl
  • Post Sorting and Ordering in Rails to BuddyMarks
  • Submit Sorting and Ordering in Rails to Slashdot
 
Keyword Advertisers:
SEO Directory SEO Links Free Link Directory Shopping Submission Directory Gardening Tips Political Forum Search Engine Optimization Search Engine Marketing Audio Video Directory SEO Forum Web Development Blog Organic SEO Wiki Web Development Consulting

Learn more about purchasing keyword text link ads on this site.