I've been looking around recently into Rails and notice that there are a lot of references to current_user
. Does this only come from Devise? and do I have to manually define it myself even if I use Devise? Are there prerequisites to using current_user
(like the existence of sessions, users, etc)?
2 Answers
It is defined by several gems, e.g. Devise
You'll need to store the user_id somewhere, usually in the session after logging in. It also assumes your app has and needs users, authentication, etc.
Typically, it's something like:
class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
This assumes that the User class exists, e.g. #{Rails.root}/app/models/user.rb
.
Updated: avoid additional database queries when there is no current user.
-
is sessions sort of like a commonly used controller/model for the purpose of controlling a users login status? or is it built into rails? Commented Oct 4, 2012 at 4:03
-
session
is built into Rails. By default, it uses a cookie to maintain a client's state between requests. See guides.rubyonrails.org/security.html#sessions for more info. Commented Oct 4, 2012 at 4:20 -
3NOTE: If you're reading this answer, be sure to include
return unless session[:user_id]
as shown in Zach's answer -- without that, everyif current_user
check while signed out will trigger another database query. Commented Jul 6, 2014 at 1:12
Yes, current_user
uses session
. You can do something similar in your application controller if you want to roll your own authentication:
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
-
is sessions sort of like a commonly used controller/model for the purpose of controlling a users login status? or is it built into rails? Commented Oct 4, 2012 at 4:02
-
1
session
is sort of likeparams
, except it persists for multiple requests. You can use it to store any sort of persistent parameter unique to your individual users (until their session expires or they log out). You can read more about it here: ActionController: Accessing the Session Commented Oct 4, 2012 at 4:14