June 26, 2024, 9:15 a.m. | Augusts Bautra

DEV Community dev.to

Sometimes you need a custom, semantic order for things, usually statuses, types. Oftentimes this is achieved with an SQL CASE statement:



sql = <<~SQL
CASE
WHEN status = 'active' THEN 0
WHEN status = 'draft' THEN 1
ELSE 99
END
SQL

order(sql, :id)


Since at least Rails 7.1 there's a better way - in_order_of!



in_order_of(:status, [:active, :draft], filter: false).order(:id)


Interestingly, v7.1 guide does not list this method at all, but it's available in edge guide.


Small caveat emptor - …

activerecord case custom draft least rails ruby semantic sql things til types you

Senior Clinical Data Scientist

@ Novartis | Home Worker

R&D Senior Data Scientist 1

@ Jotun | Sandefjord

Data Scientist - Corporate Audit, Officer

@ State Street | Toronto, Ontario

Senior Manager, Data Science & Analytics Solutions - Safety

@ Hyundai Motor America | Fountain Valley, CA, US, 92708

Data Science Working Student (all genders)

@ Merck Group | Darmstadt, Hessen, DE, 64293

Senior Data Scientist (m/f/d)

@ BASF | Limburgerhof, DE