Class Applicationcontroller < Actioncontroller::base
def Current_User
User.find (session[:user_id])
End
End
The above code is meant to define a current_user method, the function is to call the user in the Find method incoming session user_id from the database to read the current login large user information. If this method is called multiple times, the database will be accessed multiple times, an instance variable can be defined, and the results of the first call will be cached in the instance variable for the next tune use to resolve the problem of duplicate database access
Rewritten as: @current_user | | =user.find (session[:user_id])
The first call when the value of the @current_user variable is empty, perform the subsequent query database operation, and return the results to @current_user storage, the next time you call this method will not perform the query database operations, directly return the results. The efficiency is greatly improved through the code.
Caching with Instance Variables cache and instance variables