Tag: cookies

Rails + Devise and remember_me (rememberable) by default

I've wanted to add an automatic remember_me for Devise by default (without a checkbox). First I've tried to do something like this:

def create
  params[:user].merge!(remember_me: true)

Unfortunately it doesn't seem to work. I have a rememberable strategy included in my User model, but still, remember_user_token cookie was not created. I don't know why, even with remember_me option provided, it sets it to false. The easiest (and working) way to fix this, is to overwrite remember_me method, so it will always return true value.

# User of our portal
class User < ActiveRecord::Base

  devise :database_authenticatable, 
    :trackable, :encryptable, :confirmable, :recoverable,
    :registerable, :validatable, :lockable, :rememberable

  # @return [Boolean] user should be remembered when he logs in (with cookie)
  #   so he won't be asked to login again
  def remember_me

To be honest I didn't have time to investigate it more deeply, so maybe there's a better solution but this one works. After that, remember_user_token cookie is created and the session isn't lost after user closes his browser.


As Christoph mentioned in one of the comments, this is the "official" way to do this: , so probably there's no better way ;)

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑