The in_order_of method in Rails is perfect for custom database sorting, but
the downside was that in_order_of only accepted a flat list of values. If you
wanted to group multiple items at the same priority level, it was not possible.
A recent PR (#52871) fixes this limitation by allowing you to pass arrays directly into the method.
Before
Imagine you have a list of users and you want to order records by specific
groupings of their subscription plans. For instance, you might want both
:enterprise and :pro plans to rank equally and appear first, followed by
:free plans. Then, you want to sort by name within those groups. Previously,
the only way to handle this was to write a custom SQL CASE statement.
User.order(
Arel.sql(
"CASE " \
"WHEN plan_type IN (1, 2) THEN 1 " \
"WHEN plan_type = 3 THEN 2 " \
"ELSE 3 END ASC"
)
).order(:name)
After
Now, Rails will handle grouping those values together at the same rank, and
individually type cast each item. Under the hood, Rails dynamically builds the
CASE statement to match the groups.
User.in_order_of(:plan_type, [[:enterprise, :pro], :free]).order(:name)
Resources:
- Allow to pass array values to
.in_order_of(#52871)