← Back to Upcase

Best practices for default ordering in Rails 3


(Ezra Freedman) #1

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


(Jon Yurek) #2

Personally, I dislike default scopes. In my index action, I would use something like Post.for_display and have for_display be a class method that builds a scope that does what I need it to. This has the benefit of being explicit and giving things appropriate names.

On a has_many, I think I’ve used them in the past, but I would avoid them for all new code if possible.