Dinshaw Raje
Dinshaw Raje

Reputation: 953

facing issues in enum field in rails4

Hi I have generated a migration to add_column rails g migration AddColumnToEmployees

class AddColumnToEmployees < ActiveRecord::Migration
  def change
    add_column :employees, :role, "enum('SUPER-ADMIN', 'HR','ADMIN','INVENTORY','EMPLOYEE')",  :default => 'EMPLOYEE'
  end
end

run rake db:migrate Now I want to access role in my view for this I have written this:

<%=f.select :role, :collection => Employee.roles %>

But its not accessing it. It gives error undefined method 'roles' for #<Class:0xc2acd88>

Please guide how to solve this. Thanks in advance!

Upvotes: 1

Views: 110

Answers (3)

Aniee
Aniee

Reputation: 81

your migration is fine. after your migration to access it in view like that

<%=f.select :role, :collection => Employee.roles.keys.to_a %>

and define enum field in model employee.rb

enum role: {
           super_admin: 1,
           hr: 2,
           admin: 3,
           inventory: 4,
           employee: 5
       }

convert in enum role of model into hash. and assign the value. and run it.i will try my best hope it will help you!!

Upvotes: 0

Amit Sharma
Amit Sharma

Reputation: 3477

Try following code, I hope this will help you.

in AddColumnToEmployees migration file.

class AddColumnToEmployees < ActiveRecord::Migration
  def change
    add_column :employees, :role, :integer, default: 0
  end
end

in Employee Model.

class Employee
  enum role: [ :super_admin, :hr, :admin, :inventory, :employee ]
end

and finally in view file.

<%= f.select :role, options_for_select(Employee.roles.collect { |e| [e[0].humanize, e[0]] }) %>

Upvotes: 0

tirdadc
tirdadc

Reputation: 4703

I was under the impression you represented the enum as an integer in the DB, so your migration should be:

class AddColumnToEmployees < ActiveRecord::Migration
  def change
    # Assuming Employee is the first value in your enum list
    add_column :employees, :role, :integer, default: 0
  end
end

and your select should be:

<%= f.select :role, :collection => Employee.roles.keys.to_a %>

See Saving enum from select in Rails 4.1

Your model:

class Employee
  enum role: [:employee, :inventory, :admin, :hr, :superadmin]
end

Rails does automatically provide you with all potential values through a class method with the pluralized attribute name.

Upvotes: 2

Related Questions