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
The model will have three columns
status column can take any of these three distinct values
To display user books in the order of
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.
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
Rails 7 added in_order_of to Enumerable
which behaves similar to ActiveRecord
in_order_of was added to make it work on
Enumerable#in_order_of that works on Enumerators.