ActiveRecord: Order a scope by descending value without writing SQL

Posted . Visible to the public.

Instead of this:

Image.order('images.created_at DESC')

You can write this:

Image.order(created_at: :desc)

Not only do you not have to write SQL, you also get qualified column names (created_at becomes images.created_at) for free.

Multiple order criteria

To add secondary order criteria, use a hash with multiple keys and :asc / :desc values:

Image.order(title: :asc, created_at: :desc)
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-04-08 07:45)