Customizing enum fields order for ActiveRecord
ay, there is an Account
model with state
string attribute having enabled
, suspended
or disabled
value.
You can use PostgreSQL array_position
function to specify the required sorting order like so:
SELECT * FROM accounts ORDER BY array_position(array['enabled', 'suspended', 'disabled'], accounts.state)
The same query in Rails:
Account.order(Arel.sql("array_position(ARRAY['enabled' 'suspended', 'disabled'], state::text)"))
Account.pluck(:state).tally
# => {"enabled"=>45, "disabled"=>21, "suspended"=>5}
Account.order(Arel.sql("array_position(ARRAY['disabled', 'suspended'], state::text)")).pluck(:state)
References:
Somewhat related: