Reputation: 997
I keep trying to find a way to associate data with users in authlogic. I've tried everything I can think of but nothing seems to grab the data I'm trying to associate with it. Does anyone have an example that they can share? I'm currently trying to grab the currently associated email like this.
UserSessionsController:
def new
@user_session = UserSession.new
@current_User = current_user
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user_session }
end
end
user_sessions view:
<p> <%= @current_user.email %> </p>
application controller:
helper_method :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
And get this error:
undefined method `email' for nil:NilClass
about:
<p> <%= @current_user.email %> </p>
Thank you in advance for any help! It's really appreciated!
Upvotes: 0
Views: 201
Reputation: 35350
Make sure in the top of your ApplicationController
you have
class ApplicationController
helper_method :current_user_session, :current_user
Then, in your views, don't use @current_user
, use current_user
.
<p> <%= current_user.email %> </p>
When you call @current_user
in your view, it's never been set for that request, which is why you get the nil:NilClass
error.
helper_method :current_user_session, :current_user
This makes the current_user
method which is already available within all of your controllers extending ApplicationController
also available in your views as a helper method. By using current_user
, you guarantee you're being returned the current UserSession
instance. After it's been retrieved the first time (on the first call to current_user
), @current_user
will have a value, meaning
return @current_user if defined?(@current_user)
will execute, skipping the attempt to find the current UserSession
instance in subsequent calls to current_user
.
Upvotes: 1