aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/actioncontroller_basics/cookies.txt
blob: 88b99de3eebae13d30c1d150d09a13b80eff3eca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
== 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:

[source, ruby]
-----------------------------------------
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 should use `cookies.delete(:key)`.