2016-10-11 33 views
1
module SessionsHelper 

    # Logs in the given user. 
    def log_in(user) 
    session[:user_id] = user.id 
    end 

    # Returns the current logged-in user (if any). 
    def current_user 
    @current_user ||= User.find_by(id: session[:user_id]) 
    end 

    # Returns true if the user is logged in, false otherwise. 
    def logged_in? 
    !current_user.nil? 
    end 
end 

通過哈特爾的Rails的教程在8章,在那裏他可以讓你編寫代碼供用戶登錄並保持登錄。從Rails教程Ch8 - 爲什麼不使用實例變量?

在方法LOGGED_IN目前的工作?爲什麼使用局部變量current_user代替@current_user

回答

1

current_user不是局部變量,它是一種實例方法。

爲什麼不使用實例變量?

被使用。

當您調用current_user方法時,它會返回一個實例變量@current_user,它恰好是用戶對象或nil

1

這不是一個局部變量!他正在調用current_user方法,該方法返回@current_user值,因此將它關閉。您需要查看ruby中的範圍,以瞭解方法和實例變量以及局部變量如何與另一個進行交互!

相關問題