-1

I want to find the current_user who is logged in. I am using this method in application controller :

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

I can access current_user from show method in my controller but in any other method it is nil. This is strange because it was working before and now I don't know what did I do but it's not working anymore. Can anyone help me ?

kbaccouche
  • 4,575
  • 11
  • 43
  • 65
  • Do you also have `helper_method :current_user` in your application controller? – DGM Aug 25 '11 at 10:45
  • Try to find out, if it's nil, because the session[:user_id] is nil or because something other, in the special case. – Daniel Spangenberg Aug 25 '11 at 12:05
  • session[:user_id] is acting exactly like current_user : it is accessible from the show method and it's nil elsewhere. – kbaccouche Aug 25 '11 at 12:41
  • try to play with `current_user` and `@current_user` – Sergey Kishenin Aug 25 '11 at 13:02
  • @current_user is nil even in show method. I don't think that this is the problem, but what I can't understand is how is it working in show method and when I try to access it from another method in the same controller it's nil? – kbaccouche Aug 25 '11 at 13:30
  • I found the problem but I don't know how to fix it. I have this warning : WARNING: Can't verify CSRF token authenticity I am using ajax to send data to the controller, so I think that I have to send the token also but I don't know how...do you ? – kbaccouche Aug 26 '11 at 09:32

1 Answers1

0

Given your last comment, your problem is related to session only. It is not linked to the definition of you current_user method.

By default, a Rails 3 application resets the session when there is no authentication token in a HTTP POST request. The behaviour is slightly different with Rails 4 (depending on the configuration) but you would have a similar problem at the end.

I guess your ajax queries don't contain authentication token, hence the warning WARNING: Can't verify CSRF token authenticity, hence the empty session. With an empty session you current_user method will always return nil, unless you are inside a GET request and you haven't made any POST request since authentication.

I don't write a solution here because it is no simple (it depends on the javascript framework you use) and it has no link with your original question.

You should read the answer of this question: WARNING: Can't verify CSRF token authenticity rails

Community
  • 1
  • 1
Tony - Currentuser.io
  • 1,477
  • 2
  • 10
  • 7