How To: Create a guest user

Judahmeek edited this page Feb 16, 2016 · 30 revisions
Clone this wiki locally

In some applications, it's useful to have a guest User object to pass around even before the (human) user has registered or logged in. Normally, you want this guest user to persist as long as the browser session persists.

Our approach is to create a guest user object in the database and store its id in session[:guest_user_id]. When (and if) the user registers or logs in, we delete the guest user and clear the session variable. A helper function, current_or_guest_user, returns guest_user if the user is not logged in and current_user if the user is logged in.

class ApplicationController < ActionController::Base


  # if user is logged in, return current_user, else return guest_user
  def current_or_guest_user
    if current_user
      if session[:guest_user_id] && session[:guest_user_id] !=
        # reload guest_user to prevent caching problems before destruction
        guest_user(with_retry = false).reload.try(:destroy)
        session[:guest_user_id] = nil

  # find guest_user object associated with the current session,
  # creating one as needed
  def guest_user(with_retry = true)
    # Cache the value the first time it's gotten.
    @cached_guest_user ||= User.find(session[:guest_user_id] ||=

  rescue ActiveRecord::RecordNotFound # if session[:guest_user_id] invalid
     session[:guest_user_id] = nil
     guest_user if with_retry


  # called (once) when the user logs in, insert any code your application needs
  # to hand off from guest_user to current_user.
  def logging_in
    # For example:
    # guest_comments = guest_user.comments.all
    # guest_comments.each do |comment|
      # comment.user_id =
    # end

  def create_guest_user
    u = User.create(:name => "guest", :email => "guest_#{}#{rand(100)}")!(:validate => false)
    session[:guest_user_id] =


If you use this logging_in function and write the code it needs, you must customize the create action in both the sessions controller and the registrations controller by calling current_or_guest_user after super.

def create

In this way, the handoff code you write in your logging_in function will be called to transfer guest generated content to the new or returning user.

Finally in order to fix the problem with ajax requests you have to turn off protect_from_forgery for the controller action with the ajax request:

skip_before_filter :verify_authenticity_token, :only => [:name_of_your_action] 

Another option is to remove protect_from_forgery from application_controller.rb and put in each of your controllers and use :except on the ajax ones:

protect_from_forgery :except => :receive_guest

Last but not least, don't forget to add helper_method :current_or_guest_user to the controller to make the method accessible in views.

Authentication (this may interfere with the current_user helper)

If you wish to continue using before_filter :authenticate_user! and have it apply to the guest user, you will need to add a new Warden strategy. For example:

In initializers/some_initializer.rb

Warden::Strategies.add(:guest_user) do
  def valid?

  def authenticate!
    u = User.where(id: session[:guest_user_id]).first
    success!(u) if u.present?

And in initializers/devise.rb

Devise.setup do |config|
  # ...
  config.warden do |manager|
    manager.default_strategies(scope: :user).unshift :guest_user

Wait a sec... manager.default_strategies(scope: :user).unshift :guest_user makes the :guest_user strategy the first/zeroth element of the default_strategies array, which means that the :guest_user strategy is the first strategy to be run by Warden. Doesn't this mean that once session[:guest_user_id] is set, the guest_user will be the only thing authenticated, even on successful email/password login? Shouldn't the :guest_user strategy be the last Warden strategy attempted?