把RailsCasts中的視頻講的內(nèi)容總結(jié)成文章纫事,每個視頻對應(yīng)一片文章香伴,希望可以幫助到那些想要學(xué)習(xí)RailsCasts 但又被英文阻礙的同學(xué)夭拌。
使用實(shí)例變量來緩存數(shù)據(jù)
class ApplicationController < ActionController::Base
def current_user
User.find(session[:user_id])
end
end
程序中定義current_user這樣一個方法,用于獲取當(dāng)前登錄用戶萍诱,而當(dāng)在一次請求中需要調(diào)用幾次current_user方法時,對應(yīng)的也會在數(shù)據(jù)庫中查詢幾次污呼。使用實(shí)例變量緩存查詢結(jié)果則可以解決這個問題裕坊。
@current_user ||= User.find(session[:user_id])
a ||= b, 當(dāng) 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
其實(shí)并非如此,這里有一篇blog討論了這個問題苗缩。