Cookies, Sessions and Flash
HTTP has no memory. Each request arrives alone, with nothing to say that the same member signed in a minute ago. To remember anything between requests, the server asks the browser to carry a small note and send it back every time. That note is a cookie, and Rails gives you three tools built on it.
The rule
Cookies carry notes; the session keeps secrets; flash lasts one hop.
Cookies are small name-value pairs the browser stores and sends back:
cookies[:theme] = "dark" # until the browser closes
cookies.permanent[:theme] = "dark" # about 20 years
cookies.signed[:last_book_id] = @book.id # readable, but tamper-proof
cookies.encrypted[:hint] = "secret" # unreadable and tamper-proof
cookies.delete(:theme)A plain cookie can be read and changed by the user, so never trust it for anything important.
The session is a hash that Rails stores in one signed and encrypted cookie by default. The user cannot read it or change it:
session[:member_id] = member.id # on sign-in
Member.find_by(id: session[:member_id]) # on every later request
reset_session # on sign-outBecause the session lives in a cookie, it has a size limit of about 4 KB. Store small ids, not whole objects.
The flash is a special part of the session that survives exactly one more request — made for messages after a redirect:
redirect_to @book, notice: "Review posted." # sets flash[:notice]
flash.now[:alert] = "Rating is missing." # for a render in this request<p class="notice"><%= notice %></p>Rails 8's bin/rails generate authentication builds sign-in for you, using a signed cookie that points at a sessions table, so the same idea holds: store a small id, look up the rest.
The shortcut
Ask "can the member see it, may they change it, how long must it last?" Harmless and visible → plain cookie. Must be trusted → session (or signed/encrypted cookie). Only for the next page → flash.
Sign in
The password matches, so
session[:member_id] = member.idand redirect withnotice: "Welcome back".
The trap is flash with render: the message then shows on this page and the next. Use flash.now when you render.
Drills
Answer fast — trust the rule.
Why can Bookclub trust session[:member_id] but not a plain cookies[:member_id]?
What should go in the session after sign-in?
A failed save renders the form and should show "Title is missing" only on this page. What do you use?
Which call is the safest way to sign a member out?
Remember
- Cookies carry notes; the session keeps secrets; flash lasts one hop.
- Shortcut: visible, trusted or one-hop decides the tool.
- Trap: storing objects in the session, and flash instead of flash.now before a render.
