Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Devise - current_user is 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

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.

UPDATE

So thanks to the comments/answers, I have pinpointed the problem to one particular action : create.

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.

I accessed the create action through a form (submit).

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.

Could that be the cause?

UPDATE 2

In my error message, my session dump is empty, while it should contains the current_user info...

like image 636
Justin D. Avatar asked Aug 24 '13 22:08

Justin D.


2 Answers

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!

like image 102
Jose Paez Avatar answered Sep 28 '22 01:09

Jose Paez


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.

like image 29
Adam Waselnuk Avatar answered Sep 27 '22 23:09

Adam Waselnuk