Rails 2.3: default_scope
Rails 2.3 includes a new method called default_scope which provides an easy way to set default attributes on a model as it calls on records from the database. After playing around with it a bit, I am certain that I’m going to avoid using this method for a few reasons.
Before I get to that, here’s the syntax:
You could set a default_scope for any number of conditions, but
rder is really the only thing that makes sense to me (red flag number one) because nothing else would have fixed conditions for all database queries.
With this default_scope in place, we’re going to get an ORDER_BY ‘name’ ASC added to our SQL query when calling Person.all, Person.old, or Person.young. That’s all well and good until the query gets a little complex–what happens if we specify a different
rder in the named scope or in the controller? As you might guess, the default_scope loses out to specifying a different
rder in other methods.
Once your query gets complicated with includes and joins, you’ll find that suddenly the defaulted
rder option does not show up in your query and all your people are completely out of order. At that point, you’re back to square one needing to manually specify the order in a separate named_scope or in the controller logic.
The inconsistency here is intolerable, and the code also loses a lot of clarity when it is implemented since it will not work under all circumstances. Personally, I like
rder options visible in the controller (I put just about everything else in named_scopes) because the code stays clear. Just seems to me that it’s better to leave this method out all together.