Rails 7 adds ActiveRecord::QueryMethods#in_order_of


default-enum-in-rails

Rails 7 adds method in_order_of in QueryMethods, this allows you to specify an explicit order for the records.

Example usage of in_order_of

# Get ids of posts
Post.pluck(:id)
# => [1, 4, 5, 6, 7, 8]

# Using explicit order of posts
Post.in_order_of(:id, [4, 1, 5]).pluck(:id)
# => [4, 1, 5, 6, 7, 8]

Notice how it returns the order of Posts in specified order, followed by all other posts.

If we provide some column data that does not exists in ordering, it will be ignored silently. In the following example, Post with id 999 does not exists in our system.

Post.in_order_of(:id, [4, 1, 5, 999]).pluck(:id)
# => [4, 1, 5, 6, 7, 8]


Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...