在 rails4 的枚举字段中面临问题

facing issues in enum field in rails4

您好,我已经生成了迁移到 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

运行 rake db:migrate 现在我想在我的视图中访问角色,我写了这个:

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

但它无法访问它。它给出了错误 undefined method 'roles' for #<Class:0xc2acd88>

请指导如何解决这个问题。提前致谢!

我的印象是您在数据库中将枚举表示为整数,因此您的迁移应该是:

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

你的 select 应该是:

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

Saving enum from select in Rails 4.1

您的模特:

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

Rails does 通过具有复数属性名称的 class 方法自动为您提供所有潜在值。

试试下面的代码,希望对你有帮助。

AddColumnToEmployees 迁移文件中。

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

员工模型中。

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

最后在查看 文件中。

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

您的迁移没有问题。迁移后以这样的方式访问它

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

并在模型中定义枚举字段 employee.rb

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

将模型的枚举角色转换为散列。并赋值。 运行 it.i 会尽我最大的努力希望对你有帮助!!