Jump To Content

LearnHub




Action Controller: Cookies

Cookies

Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash:


class CommentsController < ApplicationController

  def new
    #Auto-fill the commenter's name if it has been stored in a cookie
    @comment = Comment.new(:name => cookies[:commenter_name])
  end

  def create
    @comment = Comment.new(params[:comment])
    if @comment.save
      flash[:notice] = "Thanks for your comment!" 
      if params[:remember_name]
        # Remember the commenter's name
        cookies[:commenter_name] = @comment.name
      else
        # Don't remember, and delete the name if it has been remembered before
        cookies.delete(:commenter_name)
      end
      redirect_to @comment.article
    else
      render :action => "new" 
    end
  end

end

Note that while for session values, you set the key to `nil`, to delete a cookie value, you use `cookies.delete(:key)`.

Articles in this guide

  1. Introduction
  2. What does a controller do?
  3. Parameters
  4. Sessions
  5. Cookies (This article)
  6. Filters
  7. Verification
  8. The request and response objects
  9. HTTP Basic Authentication
  10. Streaming and file downloads
  11. Parameter filtering
  12. Rescue

Thanks to the Ruby on Rails documentation team

This guide was written by Tore Darrell as part of the Ruby on Rails Documentation Project and is provided freely under a Creative Commons licence


Your Comment
Textile is Enabled (View Reference)