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!
Make sure in the top of your
ApplicationControlleryou haveThen, in your views, don’t use
@current_user, usecurrent_user.When you call
@current_userin your view, it’s never been set for that request, which is why you get thenil:NilClasserror.This makes the
current_usermethod which is already available within all of your controllers extendingApplicationControlleralso available in your views as a helper method. By usingcurrent_user, you guarantee you’re being returned the currentUserSessioninstance. After it’s been retrieved the first time (on the first call tocurrent_user),@current_userwill have a value, meaningwill execute, skipping the attempt to find the current
UserSessioninstance in subsequent calls tocurrent_user.