Rails Devise - current_user is nil

后端 未结 4 1202
甜味超标
甜味超标 2021-01-02 00:27

For some reason, current_user returns nil in my model-less controller (Subscriptions). I have found nothing on the Internet to justif

相关标签:
4条回答
  • 2021-01-02 01:06

    I had a similar issue but I was editing the model. So everytime I updated the model suddenly that would happen:

    current_model to nil
    

    After analyzing things, it turns out that if you leave the password in the form, when the user tries to edit some attribute, the person is then forced to write a password.
    Once the form is delivered and updated, Devise does the rational thing when someone updates a password, which is to destroy the session and ask the user to sign in again.

    So that was why current_model was suddenly turning to nil. Hope this helps, have a great day!

    0 讨论(0)
  • 2021-01-02 01:24

    Note that when you create forms using the form_tag helper, they do not automatically generate the hidden field which holds the token for CSRF authentication. I ran into this same issue with a form I had constructed using the form_tag which I sometimes prefer using.

    I fixed the issue by including the following helpers within the form:

    <%= hidden_field_tag 'authenticity_token', form_authenticity_token %>

    It's basically a manual way of generating the hidden field you need for the CSRF stuff.

    0 讨论(0)
  • 2021-01-02 01:25

    for current_user to work you need to add before_filter :authenticate_user! to your class, like:

    class SubscriptionsController < ApplicationController  
      before_filter :authenticate_user!
    
      def new
        ...
      end
    
      def create
        curent_user    # returns nil
      end
    end
    

    and the authenticate_user! method will set the current user for you :)

    0 讨论(0)
  • 2021-01-02 01:32

    It turned out the AJAX request I was making didn't carry the CSRF token. For that reason, Rails was killing my session.

    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.

    0 讨论(0)
提交回复
热议问题