Read more

ActiveRecord: Order a scope by descending value without writing SQL

Henning Koch
April 08, 2015Software engineer at makandra GmbH

Instead of this:

Image.order('images.created_at DESC')
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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)
Posted by Henning Koch to makandra dev (2015-04-08 09:45)