Caching with Instance Variables cache and instance variables

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.