4

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?

Community
  • 1
  • 1
Norto23
  • 2,249
  • 3
  • 23
  • 40

2 Answers2

2

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.

Brandan
  • 14,735
  • 3
  • 56
  • 71
  • In my app these are defined in my application controller. I couldn't get your answer to work for me but I appreciate the advice (hence the bounty awarded!) – Norto23 Apr 18 '12 at 13:57
  • Honestly, even if that had worked, it's very hacky to depend on the name of an instance variable defined in another module. Your solution is cleaner and more explicit. – Brandan Apr 18 '12 at 14:19
1

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 :)

Norto23
  • 2,249
  • 3
  • 23
  • 40