在rails4中的enum字段中遇到问题

时间:2015-05-13 11:31:15

标签: ruby-on-rails ruby-on-rails-4 enums

您好我已经生成了向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>

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

3 个答案:

答案 0 :(得分:2)

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

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

你的选择应该是:

<%= 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通过具有复数属性名称的类方法自动为您提供所有潜在值。

答案 1 :(得分:0)

尝试以下代码,希望这对您有帮助。

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]] }) %>

答案 2 :(得分: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将尽我所能,它会帮助你!