RSS Feed

Subscribe to Syndicate

Ruby on Rails Order By Using Associated Model

It is very easy to use an 'order by' clause in a model in Ruby on Rails. Supposing you have a Category model it's as simple as doing this:
 
@categories = Category.find(:all, :order => 'title')
 
But what if I need to order by the title of the subcategories after ordering by the categories title?
 
Using the category_id does not work either, because it almost sure that the categories will not be added in alphabetical order, so the command below does not work for me either:
 
@subcategories = Subcategory.find(:all, :order => 'category_id,title')
 
And neither would work the sentence below, because the resulting SQL query will fail:
 
@subcategories = Subcategory.find(:all, :order => 'category.title, title')
 
This last command will fail because rails does not recognize the Category model inside the subcategories model. So all you have to do is tell Rails that you want to include another model in the query, and this is done using the :include option from the find method:
 
@categories = Category.find(:all,:include => :subcategories, :order => 'categories.title, subcategories .title')
 
It is easy after you find out how! ;)