I’d like to know best practices for default model and association ordering in Rails 3. In Rails 2, I would use a combination of defining an order on has_many
relationships and defining default_scope
on the models, and it was easy to override these sort orders when desired (by adding an explicit order
to a call to find).
Rails 2, default sort order, newest first:
has_many :blog_posts, :order => 'created_at DESC'
To show oldest first:
blog.blog_posts.find(:all, :order => 'created_at ASC')
In Rails 3, I see that each of the above methods has the undesirable consequence of appending to the order list instead of overriding the order (the method above to show oldest first generates ORDER BY created_at DESC, created_at ASC
, rendering the override attempt useless). I’ve tried unscoped
, but that doesn’t seem elegant and on an association has the undesirable consequence of clearing any other conditions.
How do you handle default ordering in your apps? Do you always chain with an ‘order
’? Do you ever include an order on a has_many definition? Default scopes?
Thanks for your input.
Ezra