DEV Community

Augusts Bautra
Augusts Bautra

Posted on

TIL .order_values

Today I was working on adding a custom ordering to an #index view. The ordering was tricky and expensive, so I decided to only apply it as a default, and not apply it if user chooses to order by some specific column value.

Usually checking order params should suffice, but our system is a bit complexed in that ordering can come not only from request params, but also from DB memory, so I needed a way to introspect whether any ordering has been applied to a collection.

One way to achieve this would be to call .to_sql and look if the string contains ORDER BY. Luckily, Rails provides a more programmatic approach - .order_values!

MyModel.all.order_values #=> []
MyModel.all.order(id: :desc).order_values #=> [#<Arel::Nodes::Descending:0x00000001184b9c68 ..]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)