RailsCasts中文版,#1 Caching with Instance Variables 缓存实例变量

class ApplicationController < ActionController::Base
  def current_user
    User.find(session[:user_id])
  end
end
这是一个在Action中的场景,上面的代码调用User的find方法传入会话中的user_id从数据库中读取当前登陆的用户信息。如果这个方法将会在一次页面请求中重复调用多次,将意味着会多次访问数据库。通过将第一次调用时候的结果缓存在实例变量中供下次调用使用可以解决重复数据库访问导致的效率的问题。
@current_user ||= User.find(session[:user_id])
请注意实例变量后面的||(或)操作符。第一次调用这条语句时,@current_user变量没有赋过值会是nil。这时会执行后面的查询数据库操作并将返回结果赋给@current_user。接下来如果再次调用这个方法,@current_user已经有值了,便不会进行查询操作直接返回结果,代码修改带来了效率的提升。
class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find(session[:user_id])
  end
end
修改后的代码。

作者授权:You are welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.

原文链接:http://railscasts.com/episodes/1-caching-with-instance-variables

posted on 2012-11-18 22:10  边晓宇  阅读(1005)  评论(0编辑  收藏  举报