2015-05-27 48 views
1

我想在我的RoR應用程序中打印當前用戶的電子郵件。爲此,我也使用了下面的代碼:如何在Devise中定義current_user?

User.current_user 

,並打印下一個錯誤:undefined method CURRENT_USER」的#`

,但是當我用剛剛current_user它不打印任何東西。我在Google和Stack中搜索過,試圖使用它們的答案,但沒有任何結果。

如何獲取用戶電子郵件?

回答

2

在控制器中,僅current_user將返回當前登錄的用戶。因此,current_user.email將返回signed_in用戶的電子郵件。對於未登錄的用戶,current_user將返回nil。 要在控制器中打印當前用戶的電子郵件,

class TestController < ApplicationController 

    def example 
    p current_user.try(:email) # try is used because it will return nil if the user is signed in. otherwise, it will raise an error undefined method 'user' for nil class 
    end 
end 
相關問題