Ahmed Khattab
Ahmed Khattab

Reputation: 2799

What is the relation between cookies and the Rails session object?

This method remembers users by storing an encrypted cookie in the user's browser:

  def remember_user
    user.remember
    cookies.permanent.encrypted[:user_id] = user.id
    cookies.permanent.encrypted[:remember_token] = user.remember_token
  end

How is the following method able to read the user_id from the session object if I am storing it in cookies?

def index
    @user = User.find session[:user_id]
 end

Upvotes: 0

Views: 157

Answers (1)

max
max

Reputation: 102001

This whole question is based on a completely bogus premise that is easily disproven.

get 'cookie_monster/set_cookie'
get 'cookie_monster/eat_cookie'
class CookieMonsterController < ApplicationController
  def set_cookie
    cookies.permanent.encrypted[:x] = 999
    redirect_to action: :eat_cookie
  end

  def eat_cookie
    render plain: "session[:x] is #{session[:x].inspect} not #{ cookies.permanent.encrypted[:x] }"
  end
end
require 'test_helper'

class CookieMonsterTest < ActionDispatch::IntegrationTest
  test "the session is not the same thing as cookies.encrypted" do
    get "cookie_monster/set_cookie"
    follow_redirect!
    assert_equal "session[:x] is nil not 999", response.body
  end
end

The session is stored in separate session storage cookie. This is basically a hash like object that's serialized and then de-serialized on each request.

When you do cookies.permanent.encrypted[:user_id] you're setting a completely different cookie.

Upvotes: 2

Related Questions