我正在使用 authlogic
在我的 Rails 应用程序中进行身份验证。我需要能够在 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
,但我使用的是 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
这些方法似乎与您的答案中的代码完全一样,除了用户 session 实例变量被称为
@current_user_session
而不是 @user_session
就像在您的 Controller 代码中一样。如果您将用户 session 变量重命名为
@current_user_session
在您的 Controller 操作中,然后是 current_user_session
方法将短路并返回您刚刚创建的 session ,然后应该允许 current_user
返回正确用户的方法。
关于ruby-on-rails - 使用 authlogic 登录时调用 current_user 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10083027/