Reputation: 213
I have recently installed devise gem in my application. I am trying to show the current users email in a view in the application, but when i use the following in my view:
<% if user_signed_in? %>
<div>Signed in as... <%= current_user.email %></div>
<% end %>
I get an error because current_user is nil in the console. when i run user_session in the console it also returns nil, but when i run signed_in?, it returns true. I cannot figure out what is causing the application not to store the session when a user logs in.
my application controller:
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
my users model:
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
Does anyone know what could be causing this?
Update this is the error that the current_user.email throws in the view:
undefined method `email' for nil:NilClass
Upvotes: 1
Views: 316
Reputation: 102026
Of course current_user
is nil in the Rails console.
The console does not have the same context as the server does when it is processing requests. The console simply loads the configuration files and boots up the app - there is no current request or session - thus the whole concept of current_user
does not even apply.
You can of course fake it by instantiating a request object and all the rest of the environment surrounding a real request but thats a very tedious one-off way to test something that is better tested with an actual function, integration or acceptance test.
Upvotes: 1