簡體   English   中英

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>提供了錯誤的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

您的選擇應該是:

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

請參見在Rails 4.1中從選擇保存枚舉

您的模型:

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

Rails 通過具有復數屬性名稱的類方法自動為您提供所有潛在值。

嘗試下面的代碼,希望對您有所幫助。

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
       }

將模型的枚舉角色轉換為哈希。 並分配值。 並運行它。我將盡我最大的希望,它將為您提供幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM