Rails通过cookies方法来操作cookie,这和session的操作有点类似
class CommentsController < ApplicationController
def new
# 假如cookie中有评论者的姓名,则自动调用
@comment = Comment.new(author: cookies[:commenter_name])
end
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
# 设置cookie
cookies[:commenter_name] = @comment.author
else
# 删除cookie中的变量
cookies.delete(:commenter_name)
end
redirect_to @comment.article
else
render action: "new"
end
end
end
这里需要注意的是,和操作session不一样,删除cookie中的变量时不能简单的设置值为nil,而是需要显示的调用cookie.delete(:key)方法