Rails: where does the infamous "current_user" come from?

Ruby on-Rails

Ruby on-Rails Problem Overview


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)?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbigpotatoView Question on Stackoverflow
Solution 1 - Ruby on-RailsErik PetersonView Answer on Stackoverflow
Solution 2 - Ruby on-RailsZach KempView Answer on Stackoverflow