2

I have authlogic running just fine in my app, but I am rolling my own roles (i am newer to rails and wanted to learn...)

So I have a User model, a Role Model, and a User Sessions model. User acts_as_authenticated.

In my application_controller

protect_from_forgery
helper_method :current_user, :is_admin, :is_group_coach, :is_group_leader
private

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

def is_admin
  current_user.role_id == 3
end

def is_group_coach
  current_user.role_id == 2
end

def is_group_leader
  current_user.role_id == 1
end

Then I am doing a simple if is_admin in a view...

but its returning undefined method `role_id' for nil:NilClass

I think its doing this because current_user is actually running off the UserSession model not User... How can I modify this to run as expected?

TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88
  • Your user is just not logged in. Add a `before-filter` to protect actions which need logged user. Also, consider using `CanCan` gem instead of checking roles everywhere in your code. – RocketR Jul 31 '11 at 21:55

1 Answers1

0

Your current_user_session method is probably incomplete on this code snippet as you can't call find without parameters, so I'm guessing there is a guard in there against a nil value or somewhere like that if the user is not logged in. And if there is the possibility for the user to not be logged in, your methods should account for that and only call methods on current_user if one is available.

Your methods should be like this:

def is_admin
  current_user && current_user.role_id == 3
end

def is_group_coach
  current_user && current_user.role_id == 2
end

def is_group_leader
  current_user && current_user.role_id == 1
end

This will prevent the test from breaking is there is no user currently logged in on the website.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • `UserSession` is not an ActiveRecord model, it's just a class. In Authlogic they try to make it look like other models for consistency. – RocketR Jul 31 '11 at 21:51