【问题标题】:Devise - current_user nil on post request设计 - current_user nil on post request
【发布时间】:2011-10-27 00:19:23
【问题描述】:

我知道我以前也有这个工作,但由于某种原因,我的一个创建操作中的 current_user 方法调用一直返回 nil。在其他控制器等中使用时效果很好,例如显示我的用户名的侧面板。

class CombatInstancesController < ApplicationController
  def create
    # when creating a new instance, check if the current user has one and destroy it
    CombatInstance.find(current_user.combat_instance.id).destroy if current_user.combat_instance
    # Now create the new one
    render :json => current_user.create_combat_instance
  end

  def update
    @combat_instance = current_user.combat_instance
    @combat_instance.trigger_actions(params[:actions])
    @combat_instance.perform_ai_actions
    @combat_instance.save # should we instead call this in an after hook?
    render :json => @combat_instance
  end
end

CombatInstance.find(current_user.combat_instance.id).destroy if current_user.combat_instance 行是 current_user 返回 nil 的地方。工作流程是:我去主页,我登录就好了。我可以在顶部看到我的用户名,它是使用视图中的 current_user 助手生成的。但是,当我提交一个点击此处创建操作的表单时,它返回 nil。

【问题讨论】:

  • 我不确定这是否足以继续。你能提供更多细节吗?你在哪一行得到零?您遇到的确切错误/行为是什么?
  • 如果登录后刷新首页,是否还处于登录状态?如果您从create 操作的最顶部执行RAILS_DEFAULT_LOGGER.info current_user(Rails 2)或Rails.logger.info current_user(Rails 3),您会在日志中得到什么? CombatInstancesControllerApplicationController 中是否有任何 before_filters 可能导致奇怪?
  • 是的,我仍然登录。当我将创建操作顶部的 current_user 输出到日志文件时,它只输出一个空字符串。

标签: ruby-on-rails devise


【解决方案1】:

您正在使用带有 Ajax 调用的 Rails 3 吗?

确保你有

<%= csrf_meta_tag %> 

在您的标题中。

【讨论】:

  • 对这两件事都同意。该帖子是通过 ajax 调用制作的,并且我在 head 部分确实有 csrf_meta_tag。
  • 不确定你的意思。助手是内置的设计自己,所以它不是我自己定义的方法。正如我在问题中所说,助手在视图等方面工作正常。当我把它放在另一个控制器动作中时,它似乎也是如此。
  • 所以看起来令牌没有在 ajax 调用中传递。我只是将它手动添加到标题中,它可以工作:gist.github.com/1149539。可以在那里看到之前和之后的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 2015-04-01
相关资源
最近更新 更多