开发者

How can I pull the User.role_id through a UserSession Model

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 modif开发者_如何学JAVAy this to run as expected?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜