How do I order database records in rails by most recent? How do I order database records in rails by most recent? ruby-on-rails ruby-on-rails

How do I order database records in rails by most recent?


The query you posted is correct

Item.order("created_at DESC")

The only reason why it would not work is if there is anything else conflicting with it. In general, the conflict is represented by a default_scope.

If you have a default scope that overrides your order, you should first unscope the query

Item.unscoped { Item.order("created_at DESC") } 

If you are using default scopes, I strongly encourage you to avoid them. They are very hard to debug and unscope.

There are very few cases where default scopes make sense. You can simply pass the (default) scope at select time in the controller or create a custom method for it.


I realise this is a really old question, but none of the answers contain the solution without writing raw SQL, which is available since Rails 3+:

Item.order(created_at: :desc)

or using the reverse_order method:

Item.order(:created_at).reverse_order

See more at http://guides.rubyonrails.org/active_record_querying.html#orderingandhttp://guides.rubyonrails.org/active_record_querying.html#reverse-order.


I modified CDub's answer with reverse so it now works:

 Item.order(:created_at).reverse

I'm still not sure why the Rails guide's way doesn't work. Also the above method doesn't work well with pagination.