2014-10-30 54 views
1

使用rails 4.1.3和devise 3.0.4體驗一個非常奇怪的錯誤。試圖處理匿名登錄。無論是用戶通過設計登錄還是以前一種形式填寫了姓名和電子郵件。current_user在rails/devise中設置爲零

繼在控制器代碼:

logger.debug "current_user before:#{current_user.inspect}" 
    if(current_user.nil?) 
    current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email]) 
    logger.debug "Guest user created" 
    end 
    logger.debug "current_user after:#{current_user.inspect}" 

下面的日誌輸出:

D, [2014-10-30T14:10:15.627130 #2148] DEBUG -- : current_user before:#<User _id: 52ffe1b35043001fa8000000, created_at: 2014-02-15 21:52:51 UTC, updated_at: 2014-10-30 13:00:47 UTC, email: "[email protected]", encrypted_password: "$2a$10$r5wXs97N.HIAp9bp5GZBaOUt8R5.S/Z/2PhcpF0xaIVuTD4BpZrmO", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 134, current_sign_in_at: 2014-10-30 13:00:47 UTC, last_sign_in_at: 2014-10-30 12:57:35 UTC, current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: 2014-02-15 21:53:04 UTC, confirmation_sent_at: 2014-02-15 21:52:51 UTC, unconfirmed_email: nil, image: "", first_name: "Dave", last_name: "Something", roles_mask: 7> 
D, [2014-10-30T14:10:15.629130 #2148] DEBUG -- : current_user after:nil 

原來這就是我不明白,爲什麼是CURRENT_USER對象被重置到零,即使代碼中的if塊沒有被執行...

發生了什麼事?

預先感謝邁克 -

回答

1

你需要做的

sign_in(current_user) 

這樣的:

if(current_user.nil?) 
    current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email]) 
    sign_in(current_user) 
    logger.debug "Guest user created" 
end 
logger.debug "current_user after:#{current_user.inspect}" 

或設置實例變量:

if(current_user.nil?) 
    @current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email]) 
    logger.debug "Guest user created" 
end 
logger.debug "current_user after:#{current_user.inspect}" 
+0

嗨,我的問題是用戶正確登錄時t通過設計,因此current_user被定義。不知何故它被銷燬,請參閱日誌輸出。我不明白爲什麼...... – Mike 2014-10-30 13:47:17

+0

這是因爲你試圖自己創建用戶,讓devise的會話控制器爲你處理它,如果你必須改變它的代碼,那麼確保你有完全相同或幾乎相同的實現的代碼。 – Surya 2014-10-30 13:49:37