Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to order all the items in a model Item so it displays the most recent ones first. According to the Rails guide, the following code should work:

 Item.order("created_at DESC")

However, when I type that (or varieties) in the terminal, the most recent item always shows up last, and that's how they show up on my page. How do I efficiently retrieve them with he most recent first? (I'm going to display only some of them at a time on each page.)

Note that my default scope for items is oldest first.

Update: This is the SQL I get:

SELECT "comments".* FROM "comments" ORDER BY comments.created_at ASC, created_at DESC

So I guess I shouldn't use default scopes...

like image 786
am-rails Avatar asked Dec 24 '13 18:12

am-rails


1 Answers

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.

like image 93
Simone Carletti Avatar answered Sep 20 '22 20:09

Simone Carletti