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

转载于:https://www.cnblogs.com/feichan/archive/2012/03/17/2403949.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值