views:

78

answers:

1

Hey,

I implemented authentication with Authlogic and authorization with Acl9. Now I'm trying to avoid multiple hits to database to check if user is admin by keeping this in the session.

What I thought is that this code should work:

class ApplicationController < ActionController::Base
  ...
  helper_method :current_user_session, :current_user, :is_admin
  ...

  private
    def is_admin
      return current_user_session[:is_admin] if defined?(current_user_session[:is_admin])
      current_user_session[:is_admin] = current_user.has_role?(:admin)  
    end

So basically on a first call to is_admin helper method, it should add a boolean value to session[:is_admin] and then for any other calls, take it from the session. But I receive this error:

undefined method `[]=' for #<UserSession: {:unauthorized_record=>"<protected>"}>

And I stuck here. What am I doing wrong?

A: 

I had to use session[] instead of current_user_session[]. This code works as charm:

(ApplicationController)

helper_method :current_user_session, :current_user, :is_admin?
    ...
def is_admin?
    return session[:is_admin] if !session[:is_admin].nil?
    session[:is_admin] = current_user.has_role?(:admin)
end

(view template)

<% if is_admin? -%>
...

It will cache admin role in session on a first attempt and then will take it from there.

Vitaly