Rails cookie, session, flash

State management for Rails

  • cookie
  • session
  • flash

cookie

Retrieve

@email = cookies[:email]  # key(symbol)-value

Save

def cookie_rec
  cookies[:email] = {value: params[:email], expires: 3.months.from_now, http_only: true}
  render text: 'Save cookie'
end

options

  • value
  • expires
  • domain
  • path
  • secure
  • httponly

Permanent, Encrypted cookies

coolkies.permanent[:key] = { value: params[:key] }
coolkies.encrypted[:key] = { value: params[:key] }

Session

Retrieve

@item = session[:key]

Save

def session_rec
  session[:key] = params[:key]		# Use symbol
  render text: 'save session'
end

Delete

session[:key] = nil
reset_session     # Delete all session info

Flash

Keep until next request

notice

controller

def create
  format.html { redirect_to item, notice: 'Happy Item!' }
end

View

<%= notice %>

flash

flash[:key] = value

format.html {
  flash[:msg] = 'Hello world'
  redirect_to @item
}

View

<p id="notice"><%= flash&#91;:msg&#93; %></p>

Other flash methods

flash.now[:key]			# Valid only current action
flash.keep(:key)		# Keep next action
flash.discard(:key)		# Discard flash