加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用authlogic登录时为current_user调用方法

发布时间:2020-12-17 07:09:55 所属栏目:百科 来源:网络整理
导读:我在rails应用程序中使用authlogic进行身份验证.我需要能够在登录时为current_user调用方法,但它返回nil. 在我的user_sessions_controller.rb中 def create @user_session = UserSession.new(params[:user_session]) if @user_session.save current_user.inc
我在rails应用程序中使用authlogic进行身份验证.我需要能够在登录时为current_user调用方法,但它返回nil.

在我的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

它正在回归……

Failure/Error: click_button "Sign in"
     NoMethodError:
       undefined method `increment_login_count_for_current_memberships!' for nil:NilClass

我在这里看到了类似的问题Not able to set a current_user using Authlogic on Rails 3.0.1其中答案是禁用basic_auth,但我在app的管理员端使用basic_auth,所以我不能简单地禁用它.

>为什么我不能在这里调用current_user?
>如果我不能在这里调用current_user,有没有办法设置它?

解决方法

在我自己的应用程序中,我有这两个方法(以及其他)在lib / authlogic_helper.rb中定义(我假设你也这样做):

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

这些方法似乎与您的答案中的代码完全相同,除了用户会话实例变量被称为@current_user_session而不是@user_session,因为它在您的控制器代码中.

如果在控制器操作中将用户会话变量重命名为@current_user_session,则current_user_session方法将短路并返回刚刚创建的会话,然后应允许current_user方法返回正确的用户.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读