views:

934

answers:

3

I'm just learning ruby on rails and I have a table of user roles (Owner, Admin, and User). There are going to be places in the code where I need to check the user's role and show different options. Does anyone know how to do this without resorting to magic numbers or other ugly methods?

In ASP.Net web apps I've worked on I've seen this done through the use of enumerated types:

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

// ...

if (user.Role == UserRole.Admin)
    // Show special admin options

Each different role in the database is reflected as an enumerated type with a value set to the ID of that role in the database. That doesn't seem like a very good solution because it depends on knowledge of database that may change. Even if it is the proper way to handle something like this, I don't know how to use enumerated types in rails.

I would appreciate any insight into this matter.

+5  A: 

Ruby itself does not have an enumerated type, but this site shows a method http://www.rubyfleebie.com/enumerations-and-ruby/

You could make something like this in your User model:

#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
Reuben Mallaby
+3  A: 

I prefer to use the aptly named Authorization plugin for situations like this.

This will let you

permit "role"

to restrict access to roles, and

permit? "role"

to simply test for access. Both of these delegate to User#has_role?(role).

Don't feel like you have to use their ObjectRoles implementation. You can use the Hardwired roles and then implement your own User#has_role?(role) method to use your existing schema.

Ian Terrell
A: 

There's a enum plugin on rubyforge so you do:

t.column :severity, :enum, :limit => [:low, :medium, :high, :critical]

It's pretty ugly to use :limit attribute to pass parameters, but it's a more standardized way.

To install just do:

script/plugin install svn://rubyforge.org/var/svn/enum-column/plugins/enum-column

it currenctly works with Rails 2.2.2 or later. Rubyforge link: www.rubyforge.org/projects/enum-column/

Pickachu