把RailsCasts中的視頻講的內容總結成文章,每個視頻對應一片文章,希望可以幫助到那些想要學習RailsCasts 但又被英文阻礙的同學。
使用實例變量來緩存數據
class ApplicationController < ActionController::Base
def current_user
User.find(session[:user_id])
end
end
程序中定義current_user這樣一個方法,用于獲取當前登錄用戶,而當在一次請求中需要調用幾次current_user方法時,對應的也會在數據庫中查詢幾次。使用實例變量緩存查詢結果則可以解決這個問題。
@current_user ||= User.find(session[:user_id])
a ||= b, 當 a 沒有定義或者值為nil、false時,a賦值為b, 否則不賦值。
完整的程序如下
class ApplicationController < ActionController::Base
def current_user
@current_user ||= User.find(session[:user_id])
end
end
ps:
很多講Ruby的書或者文章中都介紹
a ||= b
等價于
a = a || b
其實并非如此,這里有一篇blog討論了這個問題。