How to pluck fields of Rails enum and get an array of integers?

Viewed 608

I'm using Rails 5.2.

I want to pluck an enum field and get an array of integers.

class Foo < ApplicationRecord
    enum bar: { val1: 1, val2: 2 }
end

Foo.pluck(:bar) #=> ['val1', 'val2']
Foo.pluck('foos.bar') #=> ['val1', 'val2']
Foo.pluck(:bar_before_type_cast) #=> DB error!

I can write it like Foo.pluck(:bar).map {|bar| Foo.bars[bar]} , but I want to write it more shortly.

How to achieve this?

1 Answers

You can use an alias:

Foo.pluck('bar AS f')

It'll return an array of integers.

It works based on the following from the docs:

Pluck returns an Array of attribute values type-casted to match the plucked column names, if they can be deduced.

As the value you're returning is something that can't be deduced, then its "database value" is returned instead.

Related