2016-03-15 19 views
1

我最近在我的應用程序中安裝了devise gem。我想,以顯示當前用戶在應用程序中查看電子郵件,但是當我使用我的觀點如下:Rails 4.2.2當前用戶爲零

<% if user_signed_in? %> 
<div>Signed in as... <%= current_user.email %></div> 
<% end %> 

我得到一個錯誤,因爲CURRENT_USER是零在控制檯中。當我在控制檯中運行user_session它也返回零,但是當我運行signed_in?時,它返回true。我想不出是什麼原因造成的應用程序不會話存儲在用戶登錄時

我的應用程序控制器。

class ApplicationController < ActionController::Base 
before_filter :authenticate_user! 

rescue_from DeviseLdapAuthenticatable::LdapException do |exception| 
    render :text => exception, :status => 500 
end 
# Prevent CSRF attacks by raising an exception. 
# For APIs, you may want to use :null_session instead. 
protect_from_forgery with: :exception 
end 

我的用戶模型:

class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :confirmable, :lockable, :timeoutable and :omniauthable 

before_save :get_ldap_values 

devise :ldap_authenticatable, :rememberable, :trackable, :validatable 

def get_ldap_values 
    if self.username 
    self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first if Devise::LDAP::Adapter.get_ldap_param(self.username,"mail") 
    self.display_name = Devise::LDAP::Adapter.get_ldap_param(self.username,"displayName").first if Devise::LDAP::Adapter.get_ldap_param(self.username,"displayName") 
    end 
end 
end 

有誰知道可能造成這種情況?

更新 這是錯誤的current_user.email在視圖中拋出:

undefined method `email' for nil:NilClass 

回答

1

當然current_user的是在Rails的控制檯爲零。

控制檯沒有與服務器處理請求時所處理的上下文相同的上下文。控制檯只是加載配置文件並啓動應用程序 - 沒有當前的請求或會話 - 因此current_user的整個概念甚至都不適用。

你當然可以通過實例化一個請求對象和其他所有環境實際請求來假裝它,但這是一種非常單調乏味的方法來測試一些經過實際功能,集成或驗證的更好測試測試。

+0

這樣做更有意義。我仍然可以找出爲什麼current_user.email在用戶登錄時拋出錯誤。 – N7infiltrator