为什么在 Rails 中创建销毁链接需要默认的 javascript 文件? [英] Why are default javascript files required to create a destroy link in rails?
问题描述
我今天想在 Rails 中创建一个基本的销毁"链接,所以我写了这个:
I wanted to create a basic "destroy" link in Rails today, so I wrote this:
<%= link_to "destroy me", @company, :method=>:delete
%>
生成的代码是:
<a href="/companies/1"
data-method="delete"
rel="nofollow">destroy me</a>
在我的路线中,通常的
resources :companies
我的销毁操作在我的控制器中.
And my destroy action was in my controller.
但是无论何时我点击链接,我都会被重定向到 show
操作.奇怪.
But anytime I would click on the link, I would be redirected to the show
action. Weird.
结果我没有在我的布局中包含以下行:
It turned out I didn't include the following line in my layout:
<%= javascript_include_tag :defaults %>
包含它后,销毁链接起作用了!
After including it, the destroy link worked!
为什么?为什么我需要包含默认的 javascript 标签才能完成这项工作?
Why? Why would I need to include the default javascript tags to make this work?
既然我不想使用原型,我如何只包含我需要的文件?
And since I don't want to use prototype, how do I only include the files I need?
推荐答案
从 3.0 开始,Rails 表单助手生成带有 HTML5 数据属性(在您的示例中为 data-method)的干净 HTML 标记.为了支持这些数据属性,原型需要 rails.js.如果使用 jQuery,则需要 jQuery 版本 (https://github.com/rails/jquery-ujs).
Since 3.0, Rails form helpers generate clean HTML tags with HTML5 data attributes (data-method in your example). To support these data attributes, rails.js is required for prototype. If you use jQuery, then the jQuery version (https://github.com/rails/jquery-ujs) is needed.
简单地说,rails.js 与 javascript 框架(原型或 jquery)一起做了一些魔术来钩住标签上的点击和其他事件,否则当你点击一个链接时,正常的点击会发生,因为没有 javascript,链接是正常链接.
Simply put, rails.js together with the javascript framework (prototype or jquery) does some magic to hook click and other events on a tag, other wise when you click a link, a normal click happens because without javascript, the link is a normal link.
这篇关于为什么在 Rails 中创建销毁链接需要默认的 javascript 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!