Howto redirect users based on their roles in rails 3?

1k Views Asked by At

I am trying to figure out how to redirect users on certain URL based on their role, after they log to the Ruby/Rails3 application.

So far, I have used authlogic gem for authentification and cancan gem for role setting.

Roles are just like this (defined in app/models/user.rb):

class User < ActiveRecord::Base
  acts_as_authentic
  ROLES = %w[admin customer demo]
end

Now there is app/controllers/user_session_controller.rb which is taking care of logins. I would like to make something like this:

for r in User.role
      if r == "admin"
        redirect_to admins_url
      else
        redirect_to users_url
      end
end

This is not working because of the following error:

"undefined method `role' for #<Class:0xb5bb6e88>"

Is there a simple or elegant way how to redirect users to the certain URLs according to their roles?

(Roles are defined in mysql column 'role' in the users table.)

2

There are 2 best solutions below

3
On

The for r in User.role is confusing. Are you trying to access the array of ROLES defined on the class or are you trying to access the role value of the current user?

If you are trying to access the array of ROLES, then use User::ROLES.

Using authlogic, one typically defines the current_user in the application_controller. So the role of the current user can be found using current_user.role

So your code could look something like

  if current_user.role == "admin"
    redirect_to admins_url
  else
    redirect_to users_url
  end
0
On

You should definitely check out CanCan. It is a pretty logical way to manage user roles and abilities.