def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
是@_current_user只是一個id或通過它的id找到的用戶對象?@_current_user在這裏的價值是什麼?
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
是@_current_user只是一個id或通過它的id找到的用戶對象?@_current_user在這裏的價值是什麼?
要直接回答您的問題:如果在會話中沒有:current_user_id
值,或者如果該用戶ID不存在用戶對象,則通過其ID或nil
找到用戶對象。
基本上,如果@_current_user
已經設置,那麼它不會改變它。否則,它會檢查session[:current_user_id]
是否存在/已設置,如果是,則根據&&
運算符的性質,將右側作爲表達式的值返回。右側基本上用current_user_id
查找用戶。
更簡單:如果@_current_user
尚未設定,那麼如果會話具有current_user_id
值,它設置@_current_user
到User
對象匹配的用戶ID。
如果我們假設session[:current_user_id]
是5
,那麼&&
運營商與用戶模式將返回用戶實例:如果&&
運營商的雙方都是「truthy」
> 5 && User.new(:name => 'Foo')
=> #<User name="Foo">
(指既不是未定義或false
) ,則&&
運算符返回右側值。所以@_current_user
將是User實例。
一件小事。爲什麼'@ _current_user'在'@'之後立即以'_'開頭?有沒有約定? – OneZero
@OneZero Nah,這不是我知道的約定(在Ruby中),但它可能是您所指的應用程序中使用的約定。但是,這只是一個慣例,它在語言中沒有特別的意義。 –