【问题标题】:facing issues in enum field in rails4在rails4中面临枚举领域的问题
【发布时间】:2015-07-24 15:56:30
【问题描述】:

您好,我已生成迁移到 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 #&lt;Class:0xc2acd88&gt;

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

【问题讨论】:

  • 不应该是Employee.role吗?我不认为 Rails 的属性是复数的。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您的迁移很好。在您迁移后以这样的方式访问它

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

      并在模型employee.rb

      中定义枚举字段
      enum role: {
                 super_admin: 1,
                 hr: 2,
                 admin: 3,
                 inventory: 4,
                 employee: 5
             }
      

      将模型的枚举角色转换为哈希。并赋值。并运行它。我会尽力而为,希望它对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        • 2022-07-21
        • 2015-05-21
        相关资源
        最近更新 更多