Read more

Beware of rails' reverse_order!

Judith Roth
October 06, 2016Software engineer at makandra GmbH

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

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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 by Judith Roth to makandra dev (2016-10-06 13:38)