Rails CASE WHEN in ActiveRecord
Pass the CASE expression as a string to select. ActiveRecord adds it to the column list and exposes the alias as an attribute on each record. This is the shortest route and it runs on every database.
Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.
The conversion
SQL
SELECT id, CASE WHEN total > 100 THEN 'large' ELSE 'small' END AS size
FROM orders
ActiveRecord
Order.select(:id, "CASE WHEN total > 100 THEN 'large' ELSE 'small' END AS size")
SQL that Rails 8.1.1 generates
SELECT "orders"."id", CASE WHEN total > 100 THEN 'large' ELSE 'small' END AS size FROM "orders"
A cleaner alternative
Order.select(:id, Arel::Nodes::Case.new.when(Order.arel_table[:total].gt(100)).then("large").else("small").as("size"))
Arel::Nodes::Case builds the same expression in Ruby. Use it when you assemble the condition from variables. Rails quotes the values. It is longer, so keep the string for fixed expressions.
What goes wrong
order and pluck reject raw CASE strings
Post.order("CASE WHEN ...") raises ActiveRecord::UnknownAttributeReference. Wrap the string in Arel.sql to tell Rails you checked it. pluck behaves the same way.
The alias is read-only data
order.size works because the model does not define size, but an alias that clashes with a real method is a bug. Choose a distinct name such as size_label.
Never interpolate user input into the CASE string
A string passed to select, order or pluck goes to the database as written. Build dynamic CASE expressions with Arel nodes.
Convert your own CASE WHEN query
Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.
Questions
How do I use CASE WHEN in ActiveRecord?
Call select with the CASE expression as a string and an alias, for example Order.select(:id, "CASE WHEN total > 100 THEN 'large' ELSE 'small' END AS size").
Why does order with CASE raise UnknownAttributeReference?
Rails blocks raw SQL in order and pluck unless it is wrapped in Arel.sql. Use Post.order(Arel.sql("CASE WHEN ...")).
Does ActiveRecord have a CASE helper?
Arel::Nodes::Case builds CASE expressions in Ruby. It is part of Arel, so it has no short public wrapper on the model.
Related conversions
Rails GROUP BY HAVING in ActiveRecord
Convert SQL GROUP BY with HAVING to Rails ActiveRecord using group, having and count. Tested on Rails 8.1 with the generated SQL and the Hash it returns.
Rails Window Function in ActiveRecord
Convert SQL window functions like ROW_NUMBER OVER PARTITION BY to Rails ActiveRecord. Tested on Rails 8.1, including how to filter on the window result.
Rails WHERE IN Clause in ActiveRecord
Convert SQL IN and NOT IN to Rails ActiveRecord with where(id: [..]) and where.not. Tested on Rails 8.1, including empty arrays and NULL values.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.