Devise - current_user nil on post request

2019-07-23 13:49发布

问题:

I know i had this working before, but for some reason the current_user method call in one of my create actions keeps returning nil. It works fine when used in other controller and so forth, such as a side panel to show my username.

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

The line CombatInstance.find(current_user.combat_instance.id).destroy if current_user.combat_instance is where current_user returns nil. The workflow is: I go to the home page, i login just fine. I can see my username at the top, which is generated using the current_user helper in the view. However, when i submit a form that hits the create action here, it returns nil.

回答1:

Are you using Rails 3 w/ Ajax calls?

Make sure you have

<%= csrf_meta_tag %> 

in your header.