Search code examples
ruby-on-railsdevise

How to automatically keep user remembered in Devise


I am building an app in which I would like the users to automatically be remembered on their computers, without having a "remember me" check box.

I read that I may have to call @user.remember_me!, but not sure where to call it since the Devise controllers are hidden.

I was considering adding a hidden checkbox field in the sign_in form with the checkbox marked by default, but I was hoping I could do this on the controllers side.

Any idea how this could be done?

Thanks!


Solution

  • I think customizing your devise controller is the way to go here.

    Goal: automatically set remember-me for everybody.

    First, create a devise sessions controller. Let's tell rails routes about it

    config/routes.rb

    devise_for :users, :controllers => {:sessions => 'sessions'}
    

    app/controllers/sessions_controller.rb

    class SessionsController < Devise::SessionsController
    
      def create
        params[:user].merge!(remember_me: 1)
        super
      end
    
    end
    

    This way, the user's remember me will always be set to true. yay!

    You'll then want to edit the login form to not display the remember_me checkbox.

    Also, change this in the initializer to something far off:

    #config.remember_for = 2.weeks
    config.remember_for = 1.year