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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more