When working with ActiveRecord in Rails, we sometimes expect the query results in a particular sequence/order.
Let’s say we have a Rails application for Book readers, where they keep track of the books read, currently reading and the ones which they want to read.
A simple solution to build the above
application is to create a UserBook
model.
The model will have three columns
book_id
,
user_id
,
and
status
.
status
column can take any of these three distinct values
read
,
currently_reading
and
to_read
.
Before
To display user books in the order of to_read
,
currently_reading
and
read
we might implement below code:
Either we have to write an Arel sql statement or iterate on the query records to map the final result as per the provided order.
After
Rails 7 adds in_order_of method to ActiveRecord::QueryMethods to resolve the above issue.
The above implementation with this new change will look as below:
UserBook.in_order_of
will generate the below query
But in the case of MySQL FIELD
function will be used instead of CASE
.
Rails 7 added in_order_of to Enumerable
which behaves similar to ActiveRecord in_order_of
.
ActiveRecord in_order_of
was added to make it work on ActiveRecord::Relation
objects,
unlike Enumerable#in_order_of
that works on Enumerators.