codenoob
codenoob

Reputation: 900

Database Sorting Defaults in Rails

I'm finishing up my rails app, and I notice that the some of my selects don't have the selection options in order. I'm guessing that the ones that do come out right, it's simply that I inserted the values in alphabetical order. Anyway, no surprise that they're not in alpha order, and not really that hard to fix.

My question is really about the best approach to ensuring the sort order. I think I read recently that rails (don't know why it would not depend on the database, so not sure I have this right) will pull the items in the order that they were inserted the database.

If that's is true, is it worth keeping the items in the "default" (the order you want) order and possibly even not forcing an order on the "pull"? I would think that if for many (at least in my application) cases, it would make sense to "re-sort" the order after each insert, essentially changing the original insert order. That way, whether you're calling the re-sort the order, it will be faster.

Does this even make sense? Can you tell a database to "re-sort" the items in the manner discussed? Thoughts?

Thanks.

Upvotes: 0

Views: 69

Answers (1)

Danny
Danny

Reputation: 6025

The order in which postgresql returns the records is unspecified. (see http://www.postgresql.org/docs/9.1/static/queries-order.html). You can add a default sort order though to your model, using default_scope. E.g.

default_scope order('created_at DESC')

Upvotes: 1

Related Questions