Rails Cookie和session使用

来源:互联网 发布:阿里云ecs 共享改独享 编辑:程序博客网 时间:2024/05/29 18:36

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  endend

这里需要注意的是,和操作session不一样,删除cookie中的变量时不能简单的设置值为nil,而是需要显示的调用cookie.delete(:key)方法


0 0
原创粉丝点击