Old Monk Old Monk - 2 months ago 8
Ruby Question

Rails enum integrated with Postgres

I have a

User
model, which will have
designation
as attribute.

I have created a
Enum
in
Postgres
and made
designation
as
enum
.

Here is migration file.

class AddDesignationToUsers < ActiveRecord::Migration
def change
execute <<-SQL
CREATE TYPE user_designations AS ENUM ('Newbie', 'Coder', 'Owner', 'Lead', 'Architect');
SQL

add_column :users, :designation, :user_designations
end
end


I have also designation as enum in model file
User.rb


enum designation: { newbie: 'Newbie' , coder: 'Coder', owner: 'Owner',
lead: 'Lead', architect: 'Architect' }


Now when I am trying to get designation of a User, by say
User.first.designation
. I am getting value
coder
instead of
Coder
.

But when I just type
User.first
in console, I can see the value of designation as
Coder
, which is expected. But I don't why it is getting messed up while extracting it using
User.first.designation
.

Please hep me where I am doing it wrong.

dkp dkp
Answer

This is an issue with Rails 4 and this has been fixed in Rails 5 as per this patch.

You can anyway do this to get the enum value in Rails 4:

User.first[:designation]