#reverse_order
does not work with complex sorting constraints and may even silently create malformed SQL for rails < 5.
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 11:38)