Rails - How to override devise SessionsController to perform specific tasks when user signs in?

Patrice Navarre picture Patrice Navarre · Dec 12, 2012 · Viewed 43.9k times · Source

Using Devise to manage users sessions / registrations I would need to perform specific tasks (updating some fields in the users table for this specific user for example) each time a user signs in, and before he gets redirected by devise to the home page for connected users.

Do I have to override devise SessionsController, and if yes, how?

Answer

Pykih picture Pykih · Dec 12, 2012

Alternatively, you can create your own sessions controller

class SessionsController < Devise::SessionsController
  def new
    super
  end

  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    if !session[:return_to].blank?
      redirect_to session[:return_to]
      session[:return_to] = nil
    else
      respond_with resource, :location => after_sign_in_path_for(resource)
    end
  end
end

And in routes.rb add:

devise_for :users, controllers: {sessions: "sessions"}