title: Rails 5: cache user role info at login and flush it at logout
body: <p>I'm trying to implement role info caching starting from login to logout.</p>
  
  <p>In my models/role.rb I have this:</p>
  
  <pre><code>class Role &lt; ApplicationRecord
    belongs_to :user, optional: true
    accepts_nested_attributes_for :user
  
  class &lt;&lt; self
      def all_cached
      Rails.cache.fetch("roles") { Role.where(user_id: current_user) }
      end
  end
  
  private
  
  def flush_cache
      Rails.cache.delete('roles')
  end
  </code></pre>
  
  <p>In my controllers/roles_controller.rb I have this:</p>
  
  <pre><code>def roles
    @roles = Role.all_cached
  end
  </code></pre>
  
  <p>In my controllers/sessions_controller.br I have this:</p>
  
  <pre><code>class SessionsController &lt; ApplicationController
   def new
    render :layout =&gt; "empty"
   end
  
   def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user &amp;&amp; user.authenticate(params[:session][:password])
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      redirect_back_or user
    else
      flash.now[:error] = 'Invalid email/password combination!'
      render 'new', :layout =&gt; "empty"
    end
   end
  
   def destroy
    log_out if logged_in?
      redirect_to login_path
    end
  end
  </code></pre>
  
  <p><strong>How do I set current_user role is cached at login and deleted at logout?</strong> I want to cache it once for the whole user session so I can retreive info at any time for checking user roles and permissions. I do not want to store this info in session as it is quite a lot of info + not sure if that is safe.</p>