Rails枚举类型或替代

Jas*_*son 26 enums ruby-on-rails

我只是在rails上学习ruby,我有一个用户角色表(所有者,管理员和用户).在代码中将有一些地方需要检查用户的角色并显示不同的选项.有没有人知道如何做到这一点,而不诉诸魔术数字或其他丑陋的方法?

在ASP.Net网络应用程序中,我已经通过使用枚举类型看到了这一点:

public enum UserRole { Owner = 1, Admin = 2, User = 3 }

// ...

if (user.Role == UserRole.Admin)
    // Show special admin options
Run Code Online (Sandbox Code Playgroud)

数据库中的每个不同角色都反映为枚举类型,其值设置为数据库中该角色的ID.这似乎不是一个非常好的解决方案,因为它取决于可能会改变的数据库知识.即使这是处理这样的事情的正确方法,我也不知道如何在rails中使用枚举类型.

我很感激对这件事的任何见解.

Reu*_*aby 26

Ruby本身没有枚举类型,但是这个站点显示了一个方法http://www.rubyfleebie.com/enumerations-and-ruby/

你可以在你的用户模型中做这样的事情:

#constants
OWNER = 1
ADMIN = 2
USER = 3

def is_owner?
  self.role == OWNER
end

def is_admin?
  self.role == ADMIN
end

def is_user?
  self.role == USER
end
Run Code Online (Sandbox Code Playgroud)


Dim*_*tis 13

Rails 4.1中添加的功能是否可以满足您的需求?

http://coherence.io/blog/2013/12/17/whats-new-in-rails-4-1.html

从博客文章复制:

class Bug < ActiveRecord::Base
  # Relevant schema change looks like this:
  #
  # create_table :bugs do |t|
  #   t.column :status, :integer, default: 0 # defaults to the first value (i.e. :unverified)
  # end

  enum status: [ :unverified, :confirmed, :assigned, :in_progress, :resolved, :rejected, :reopened ]

...

Bug.resolved           # => a scope to find all resolved bugs
bug.resolved?          # => check if bug has the status resolved
bug.resolved!          # => update! the bug with status set to resolved
bug.status             # => a string describing the bug's status
bug.status = :resolved # => set the bug's status to resolved
Run Code Online (Sandbox Code Playgroud)