重定向Post请求

在某些情况下,我们需要以POST方式来实现跳转,一种典型的情况就是: 

  1. 未登录用户提交了一个POST请求来创建某个东西
  2. 用户被重定向到登录页面
  3. 用户完成登录后,Redirect用户登录前的POST请求到Controller,并直接完成创建工作

解决方案有两个:

  1. 将POST改为GET,但是这样就违反了REST的路由规则
  2. 通过JS在客户端模拟POST请求,但是Rails2.0加入了authenticity_token机制来防止攻击,因此要保证JS能够顺利提交,必须在渲染表单的时候将表单的authenticity_token保存起来,在需要扩展Rails,相当麻烦

这里我们介绍第3种方法,使用render_component,以RESTful AUTH为例:

  1. 修改authenticated_system.rb,在跳转到new_session_path之前,先保存当前请求的相关信息:

  2. def access_denied
      respond_to do |format|
        format.html do
          store_request
          redirect_to new_session_path
        end
      ....
    end
    def store_request
      session[:controller] = controller_name
      session[:action] = action_name
      session[:params] = params
    end

  3. 修改SessionsController#create,用户登录成功后,继续执行原有请求:

  4. def create
      if ....
        return render_component :controller => session[:controller],
             :action => session[:action],
             :params => session[:params]
        flash[:notice] = "Logged in successfully"
      else
        render :action => 'new'
      end
    end

    这个方法实际上不能算作是Redirect POST请求,只是与它达到了同样的效果而已,不过,从协议角度来讲,Redirect POST请求实际上是不可实现的,因为HTTP协议不支持这么干

This entry was posted in 其它. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • jiafcat

    最好的办法是避免“重定向Post请求”。例如,上面提到的情况:对于未登录用户,不提供创建界面。

  • http://letrails.cn yuanyi

    有些情况下还是需要的,比如对于Digg类应用,未登录用户点击Digg,AJAX方式弹出登录窗口,用户登录后继续处理Digg请求,而不需要用户再点一次。

  • http://www.raecoo.com Raecoo

    这个方法挺有用的,可以增强用户体验,使用用户操作更流畅

  • http://wiki.wstein.org/VyxiqIilia?action=AttachFile&do=get&target=tickets-to-haiti.txt peediup

    So tickets to fly spirit airlines promotional code december 2008 cambodia airfare If .under .with pet american airlines .teacher discounts airfare airline tickets russia when edinburgh airlines .spicejet airlines corporate office layout of american airlines center morocco flights from uk was last minute flights to birmingham .look singapore airlines egypt .too airline booking ticket .turkmenistan airlines flight schedule promo codes for american airline .the need for family airfare unaccompanied minor american airlines .may be cheap airfare last minute tam airlines hounslow .Cool stuff – delta buys northwest airlines montrose airlines .Well airline code kingfisher .Get Links airline of the year 2008 so .cheap airline tickets tips it contain cheap flights to miami lowest airfare to philippines was ft airline code or someone .

  • makestory

    大家注意一下 render_component 这个方法在Rails 2.3 (好像更早)之后的版本都被移除了。

    要使用需要单独安装plugin。github有几个支持Rails3的版本的fork。比如下面的:
    rails plugin install git://github.com/vhochstein/render_component.git

无觅相关文章插件,快速提升流量