zoukankan      html  css  js  c++  java
  • rails3的删除问题

    Rails 3所做的很大一个改进就是:Unobtrusive JavaScript(非侵入式的JavaScript),以实现对HTML和JavaScript代码的分离。比如:

    1 <%= link_to "Destroy", @product, :confirm => "Are you sure?", :method => :delete %>

    将转换成:

    <a href="/products/8" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a>

    不再有多余的js代码,不过那个data-是html5的元素,因此这段代码要跑起来还是有点困难的。在windows上,点击destroy会跳到show的action中去。

    引用:
    The reason that the link isn’t working is that we don’t have the relevant JavaScript files referenced in the head section of the page so the link will behave as a standard link and perform a GET request as there’s nothing telling it to do otherwise.

    : n4 I0 L/ G) V% M' D( F6 j, |4 @
    也就是说浏览器把 它当做get方法处理了。在linux ubuntu下,虽然执行了delete操作,但是没有authenticity_token元素,会被认为是CSRF攻击,因此会抛出 InvalidAuthenticityToken异常。这个问题让我想起过加skip_before_filter :verify_authenticity_token,但是这明显不是好的方式,也试着改一下 request.forgery_whitelisted?方法,虽然也能解决问题,但更加的不好。无意间在网上看见了一种处理方式,这种方式应该是标准 的解决方案了吧。
    解决方式很简单,在layouts目录下的模板文件的头部加上:

    <%= javascript_include_tag :defaults %>     
    <%= csrf_meta_tags %>

    一般第一句是有的,只是缺少第二句。看看csrf_meta_tag源码:

    def csrf_meta_tag   

    if protect_against_forgery?
    %(<meta name="csrf-param" content="#{Rack::Utils.escape_html(request_forgery_protection_token)}"/>\n<meta name="csrf-token" content="#{Rack::Utils.escape_html(form_authenticity_token)}"/>).html_safe
    end

    end

    相应的html代码与下面类似:

    <meta name="csrf-param" content="authenticity_token"/><meta name="csrf-token" content="WO8dau2vScU/ad3JKLh2jRdSm7N8QEdNfX3ggGawxOE="/>

    这段代码主要解决的就是csrf的问题。在原来的rails2中,通过js创建一大段代码来提交删除操作,提交方式为post,其中就有这个隐藏字段,所以原因是可能没有这个不能识别到delete操作吧。 : s3 {# j. {0 Z+ l3 Z, g


    / c4 {: E& X, i2 @) Q9 R

  • 相关阅读:
    JavaScript 类私有方法的实现
    sublime小程序插件
    显示引擎innodb状态详解
    JAVA学习资料大全
    mongo-aggregate命令详解
    PHP error_reporting
    mongo基本命令
    php56升级后php7 mcrypt_encrypt 报错
    docker 基础命令
    敏捷建模:增强沟通和理解
  • 原文地址:https://www.cnblogs.com/feichan/p/2403949.html
Copyright © 2011-2022 走看看