问题描述
出于某种原因,current_user
在我的无模型控制器 (Subscriptions
) 中返回 nil
.我在互联网上找不到任何可以证明这种行为的理由...
For some reason, current_user
returns nil
in my model-less controller (Subscriptions
). I have found nothing on the Internet to justify this behavior...
class SubscriptionsController < ApplicationController
def new
...
end
def create
current_user # returns nil
end
end
我有一个 csrf 元标记:
I have a csrf meta tag :
<meta content="xxx" name="csrf-token">
我可以提供更多代码,但我不确定什么会有用.
I can provide more code, but I'm not sure what would be useful.
更新
多亏了评论/答案,我已经将问题定位到一个特定的操作:create
.
So thanks to the comments/answers, I have pinpointed the problem to one particular action : create
.
如果我将 @user = current_user
添加到 new
,我可以在我的 new
视图中显示当前用户的电子邮件.但是,在我的 create
控制器中,current_user
返回 nil
.
if I add @user = current_user
to the new
, I can show the current user's email in my new
view. However, in my create
controller, current_user
returns nil
.
我通过表单(提交)访问了 create
操作.
I accessed the create
action through a form (submit).
在提交表单之前,我验证输入,然后向 Stripe 发送请求以从表单中获取令牌.如果没有错误(验证和条带),我就会发送表单.
Before the form is submitted, I validate the input and then send a request to Stripe to get a token out of the form. If there are no errors (validation and stripe), I then send the form.
这可能是原因吗?
更新 2
在我的错误消息中,我的会话转储是空,而它应该包含 current_user 信息...
In my error message, my session dump is empty, while it should contains the current_user info...
推荐答案
结果我发出的 AJAX 请求没有携带 CSRF 令牌.出于这个原因,Rails 正在扼杀我的会话.
It turned out the AJAX request I was making didn't carry the CSRF token. For that reason, Rails was killing my session.
我在我的 SubscriptionsController
中添加了 skip_before_filter :verify_authenticity_token
并且它现在可以工作了.它可能不是最安全的解决方案,但它目前有效,所以我会继续开发并稍后再回到这个问题.
I added skip_before_filter :verify_authenticity_token
in my SubscriptionsController
and it is now working. It might not be the most secure solution, but it works for now, so I continue to develop and come back to this issue later.
这篇关于Rails Devise - current_user 为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!