0

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.

Old Monk
  • 35
  • 3
  • *" it is getting messed up while extracting it using User.first.designation"* What do you mean, **"messed up"**? What are you expecting to see? What are you seeing instead? – Tom Lord Sep 23 '16 at 09:43
  • "Now when I am trying to get designation of a User, by say User.first.designation. I am getting value coder instead of Coder." – Old Monk Sep 23 '16 at 09:44
  • Expecting Coder with CAPITAL 'C' instead of small – Old Monk Sep 23 '16 at 09:45
  • An obvious guess is that this is because you defined the mapping: `coder: 'Coder'`, instead of `Coder: 'Coder'`. However, I'm a little confused why you are defining an enum of strings, rather than the standard enum of integers -- i.e. `enum designation: %w(newbie coder owner lead architect)`, so each value is actually stored as an integer in the database. – Tom Lord Sep 23 '16 at 09:51
  • `User.first[:designation]` - What does this return to you ? – dp7 Sep 23 '16 at 10:01
  • @dkp that worked!! :) – Old Monk Sep 23 '16 at 10:21
  • @OldMonk great & I will extend it as an answer. – dp7 Sep 23 '16 at 10:22
  • @TomLord Some designation will be with space, such as 'Tech Architect'. These values can be put in postgres enum, but won't if using vanilla enum using rails – Old Monk Sep 23 '16 at 10:23
  • @OldMonk I'm sure you are not using Rails 5, what is your Rails version ? – dp7 Sep 23 '16 at 10:24
  • @dkp Yes I am using 4.2. Is it resolved in Rails 5?? – Old Monk Sep 23 '16 at 10:33
  • @OldMonk yes, it should work in Rails 5! – dp7 Sep 23 '16 at 10:35

1 Answers1

2

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]
dp7
  • 6,651
  • 1
  • 18
  • 37