homeASCIIcasts

1: Caching With Instance Variables. 

(view original Railscast)

Other translations: It Fr Es Kr Pl Pt

	class ApplicationController < ActionController::Base
		def current_user
			User.find(session[:user_id])
		end
	end

The method above fetches the currently logged-in user. It performs a find on the User model for the session’s user_id. This method is called several times per request, which means that the database is also called several times per request. This problem can be solved by caching the result of the database call in an instance variable.

@current_user ||= User.find(session[:user_id])

The important thing to note is the OR symbol. The first time the line above is called, the @current_user variable will be nil and so the database call will be made. For all subsqeuent calls to the same method, @current_user will contain the current user so the request to the database won’t be made. This will improve performance.

class ApplicationController < ActionController::Base def current_user @current_user ||= User.find(session[:user_id]) end end

The updated action with the instance variable used.