简体   繁体   English

使用AuthLogic在ROR中创建会话后,current_user为nil

[英]Current_user nil after creating a session in ROR with AuthLogic

I'm having a bit of problems with AuthLogic and current_user. 我在AuthLogic和current_user方面遇到了一些问题。

I have a Flex4 application using the Cairngorm framework as the front-end, and Ruby On Rails as the back-end. 我有一个使用Cairngorm框架作为前端,使用Ruby On Rails作为后端的Flex4应用程序。

I can log in fine through a browser, and when only using ROR. 仅使用ROR时,我可以通过浏览器登录。 However, when I try it through my Flex4 application, it will fail the first time but work the second time. 但是,当我通过Flex4应用程序尝试它时,它将第一次失败,但是第二次可以工作。

What is happening, is inside the user_sessions_controller.rb I have a call to 发生了什么,在user_sessions_controller.rb内,我打电话给

self.current_user.to_xml;

The first time I call the create action, the current_user object returns nil. 我第一次调用create动作时,current_user对象返回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. 因此,这使我相信在我的create动作中的render命令之后的某个时间设置了current_user。

If I need my rails controller to return the current user in the create action, how would I go about doing that? 如果我需要用rails控制器在create动作中返回当前用户,我该怎么做呢?

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... 只是有完全相同的问题...不确定为什么会发生这种情况,但是我试图在我的user_sessions_controller.rb create方法中调用current_user,如下所述解决了...

  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! 希望这可以帮助!

This is because the helper methods current_user is typically defined as a before_action. 这是因为辅助方法current_user通常被定义为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. 我还使用了这个UserSession.find.user,它非常适合此用例。

Cheers, Niklas 干杯,尼克拉斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM