2014-12-07 31 views

回答

3

試試這個: 您實際上需要將變量存儲在會話中。 以CURRENT_USER它自身的例子: - 在您的應用控制器(/app/controllers/application_controller.rb)添加一個輔助方法如下:

class ApplicationController < ActionController::Base 

    protect_from_forgery 

    helper_method :current_user 

    private 
    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 
end 

的CURRENT_USER方法,通過其ID獲取當前用戶,使用會話變量中的id,並將結果緩存到實例變量中。我們也將它作爲一個輔助方法,以便我們可以在應用程序的視圖代碼中使用它。

參考 - http://railscasts.com/episodes/250-authentication-from-scratch?view=asciicast