1

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!

Dinshaw Raje
  • 933
  • 1
  • 12
  • 33

3 Answers3

2

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.

Community
  • 1
  • 1
tirdadc
  • 4,603
  • 3
  • 38
  • 45
0

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]] }) %>
Amit Sharma
  • 3,427
  • 2
  • 15
  • 20
0

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!!

Aniee
  • 81
  • 12