Current_user nil after creating a session in ROR w

2019-06-26 09:40发布

I'm having a bit of problems with AuthLogic and current_user.

I have a Flex4 application using the Cairngorm framework as the front-end, and Ruby On Rails as the back-end.

I can log in fine through a browser, and when only using ROR. However, when I try it through my Flex4 application, it will fail the first time but work the second time.

What is happening, is inside the user_sessions_controller.rb I have a call to

self.current_user.to_xml;

The first time I call the create action, the current_user object returns nil. The second time I call it (without restarting the server, or browser) it will be the proper current user.

So this leads me to believe that the current_user is being set sometime after the render command inside my create action.

If I need my rails controller to return the current user in the create action, how would I go about doing that?

2条回答
Animai°情兽
2楼-- · 2019-06-26 10:08

This is because the helper methods current_user is typically defined as a before_action. What means, the before action did not run before you use it during the session create.

I also used this UserSession.find.user which is perfectly fine for this usecase.

Cheers, Niklas

查看更多
Explosion°爆炸
3楼-- · 2019-06-26 10:13

Was just having the exact same problem...not sure why this happens but I was trying to call current_user in my create method in my user_sessions_controller.rb, solved as per below...

  def create
    @user_session = UserSession.new(params[:user_session])

    if @user_session.save
      current_user = UserSession.find.user
      current_user.increment_login_count_for_current_memberships!
      flash[:notice] = 'Sign in successful.'
      redirect_to root_path
    else
      render action: "new"
    end
  end

Hope this helps!

查看更多
登录 后发表回答