Sometimes it’s convenient to ensure that all rows in a database table are always retrieved in a specified order for consistency. It turns out that this is trivial to do in Rails (both Rails 2.3.x and Rails 3.x).
I had a SETTINGS table in the database that defined the settings that were available in order to customize a product. Anywhere that those settings were listed, I wanted them to be listed in alphabetical order.
In standard Rails fashion, I had a Setting model that corresponded to the database table. As shown below, a default scope can be defined that will automatically be applied whenever find is called for the model (unless overridden by the caller).
Listing 1: The Setting Model (Rails 2.3.x)
class Setting < ActiveRecord::Base
default_scope :order => 'name'
end
Listing 2: The Setting Model (Rails 3.x)
class Setting < ActiveRecord::Base
default_scope order(:name)
end
That’s it. One line of code in Rails 2.3.x or Rails 3.x, and my objective was achieved throughout my entire application.
On another note, AREL can be used in Rails 3.x to chain conditions:
default_scope where(:deleted_at => nil).order(:name)
Should you need to override a default scope in Rails 3.x, here’s how:
Setting.with_exclusive_scope.order(:created_at).all
Default scopes can be useful and convenient, just don’t overuse them.
