简体   繁体   English

Rails-会话中的ACL9缓存

[英]Rails - ACL9 caching in session

I implemented authentication with Authlogic and authorization with Acl9. 我使用Authlogic实现了身份验证,并使用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. 因此,基本上在第一次调用is_admin helper方法时,它应该为session[:is_admin]添加一个布尔值,然后对于其他任何调用,请从会话中获取它。 But I receive this error: 但我收到此错误:

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

And I stuck here. 我被困在这里。 What am I doing wrong? 我究竟做错了什么?

I had to use session[] instead of current_user_session[]. 我不得不使用session []而不是current_user_session []。 This code works as charm: 这段代码具有魅力:

(ApplicationController) (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. 它将在第一次尝试时在会话中缓存管理员角色,然后从那里接管它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM