Introduction

ar_orderable is a small ActiveRecord addition that makes ordering of results easier and cleaner.

Supported features are:

  • Ordering by an attribute in associated model (belongs_to or has_one)
  • Ordering by multiple attributes
  • Defaults to case-insensitive ordering (a < B), optionally case-sensitive
  • Direction can be specified, defaults to ascending
  • Protects from SQL injection by checking the attribute to order by is in a predefined set of orderable attributes

Tested with ActiveRecord 2.3.5. Should work without hassle using any 2.3.x version of ActiveRecord. Support for ActiveRecord 3.0.x is upcoming.

Supported & tested database adapters include PostgreSQL, MySQL and SQLite3. Might work with others.

Installation

Using Bundler with Rails 2.3.x add this to your Gemfile:


  gem "ar_orderable", :require => "orderable"

As plugin:


  ./script/plugin install git://github.com/mnylen/ar_orderable.git

Usage

In model:


class Game < ActiveRecord::Base
  belongs_to :developer
  orderable :by => [:name, :"developer.name"], :default => :name
end

In controller:


Game.order(:name) # or Game.order("name")  

To order by association’s attribute:


Game.order(:"developer.name") # or Game.order("developer.name")

To order in descending order:


Game.order(:"name!desc") # or Game.order("name!desc")

To order in case-sensitive manner:


Game.order(:name, :case_sensitive => true)

To order by multiple attributes:


Game.order([:"developer.name", :name]) # orders results first by developer name, then by game name

If trying to order by an attribute that is not orderable by, it will order by the default attribute:


Game.order(:updated_at) # will order by name