Read more

Beware of rails' reverse_order!

Deleted user #4117
October 06, 2016Software engineer

#reverse_order does not work with complex sorting constraints and may even silently create malformed SQL for rails < 5.

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

Take a look at this query which orders by the maximum of two columns:

Page.order('GREATEST(pages.published_from_de, pages.published_from_en) DESC').to_sql
# => SELECT "pages".* FROM "pages" ORDER BY GREATEST(pages.published_from_de, pages.published_from_en) DESC

Rails 4

Rails 4 will not immediately raise but creates malformed SQL when trying to use reverse_order on this query:

Pageorder('GREATEST(pages.published_from_de, pages.published_from_en) DESC').reverse_order.to_sql
# => SELECT "pages".* FROM "pages"  ORDER BY GREATEST(pages.published_from_de DESC, pages.published_from_en) ASC

This will fail as soon as you want to execute the query (syntax error at or near "DESC").

Rails 5

Rails 5 raises an IrreversibleOrderError.

Page.order('GREATEST(pages.published_from_de, pages.published_from_en) DESC').reverse_order.to_sql
# => ActiveRecord::IrreversibleOrderError: Order "GREATEST(pages.published_from_de, pages.published_from_en) DESC" can not be reversed automatically
Posted to makandra dev (2016-10-06 13:38)