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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)