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.

11
  • " 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? Commented Sep 23, 2016 at 9: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." Commented Sep 23, 2016 at 9:44
  • Expecting Coder with CAPITAL 'C' instead of small Commented Sep 23, 2016 at 9: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. Commented Sep 23, 2016 at 9:51
  • User.first[:designation] - What does this return to you ? Commented Sep 23, 2016 at 10:01

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.