Reputation: 2269
I am using authlogic
for authentication in my rails app. I need to be able to call a method for the current_user when they sign in but it's returning nil.
In my user_sessions_controller.rb
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
current_user.increment_login_count_for_current_memberships!
flash[:notice] = 'Sign in successful.'
redirect_to root_path
else
render action: "new"
end
end
And it's returning...
Failure/Error: click_button "Sign in"
NoMethodError:
undefined method `increment_login_count_for_current_memberships!' for nil:NilClass
I've seen a similar problem here Not able to set a current_user using Authlogic on Rails 3.0.1 where the answer was to disable basic_auth
, but I am using basic_auth
for my admin side of the app so I cannot simply disable it.
Why can't I call the current_user
here?
If I can't call current_user
here, is there a way to set it?
Upvotes: 4
Views: 447
Reputation: 2269
I still don't know why I cannot call current_user
or @current_user
here. But I found two ways to call the current_user here in the controller code...
UserSession.find.user.increment_login_count_for_current_memberships!
and
@user_session.user.increment_login_count_for_current_memberships!
If anyone wants to shed some light on why I can't call current_user
here, I'll happily award you the bounty :)
Upvotes: 1
Reputation: 14983
In my own app, I have these two methods (among others) defined in lib/authlogic_helper.rb
(and I'm assuming you do too):
module AuthlogicHelper
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.user
end
end
Those methods seem to do exactly what the code in your answer does, except that the user session instance variable is called @current_user_session
instead of @user_session
as it is in your controller code.
If you rename your user session variable to @current_user_session
in your controller action, then the current_user_session
method will short-circuit and return the session you just created, which should then allow the current_user
method to return the correct user.
Upvotes: 2