ActsAsSortable is a plugin to allow easy sorting of active record models on (selected) attributes.
Run the following command:
rails plugin install git://github.com/ygor/acts_as_sortable.git
For your model(s) that you want to allow to be sorted, just add the mixin and pass the names of the attributes, class methods or scopes that can be used for sorting:
class Book < ActiveRecord::Base # attributes: name, author and genre ... acts_as_sortable :name, :'author.name', :genre # if you do not pass any parameters, all valid attributes and scopes are available for sorting ... end
Then use the following to sort:
@books = Book.sorted('name', 'asc').all # sorts all books by name ascending @books = Book.sorted(['name', 'asc']).all # other possibility
Or pass multiple sort keys:
@books = Book.sorted(['author.name', 'asc'], ['name', 'desc']).all # sorts all books by author name ascending, followed by name descending @books = Book.sorted([['author.name', 'asc'], ['name', 'desc']]).all # same as above, different way of passing parameters @books = Book.sorted('author.name', 'asc', 'name', 'desc').all # third way of calling sorted
You can also call sorted on a scope model, e.g.
@books = Book.where('name != "").joins(:author).sorted('name', 'desc').all # sorts all books by author name ascending, followed by name descending