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