Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5886 posts at DZone. View Full User Profile

A Caching Current User Method Call

12.23.2007
Email
Views: 5763
  • submit to reddit
        A simple method that returns the current user and caches the result to reduce database hits.  This assumes you're storing user information in User and that the current user is identified by the session variable user_id.
class ApplicationController < ActionController::Base
  def current_user
    session[:user_id] ? @current_user ||= User.find(session[:user_id]) : nil
  end
end