3

我在使用 Rails 4、Turbolinks 和远程表单时遇到了一个相当奇怪的问题。我有一个看起来像的表格:

<%= form_for [object], remote: true do |f| %>                                                   
    <td><%= f.text_field :name, class: 'form-control' %></td>                                     
    <td><%= f.email_field :email, class: 'form-control' %></td>                                   
    <td><%= f.submit button_name, class: 'btn btn-sm btn-primary' %></td>
<% end %>    

此表单添加(创建)一个新对象。然而,它并不总是有效:

  • 当我直接使用 URL 或刷新加载页面时;有用
  • 当我从我的应用导航到此页面时;它失败

禁用此链接的 Turbolinks 时,该页面运行良好。

我有两个问题:

  1. 为什么这不起作用?这是因为远程处理程序由于 JQuery/Turbolinks 问题而没有附加到按钮上吗?
  2. 我该如何解决这个问题?

提前致谢。

解决方案

感谢@rich-peck,解决方案是添加一段javascript,在单击按钮时手动提交表单:

<%= javascript_tag do %>
  var id = "#<%= dom_id(f.object) %>";
  var inputs = $(id).parent().find('input');
  console.log(inputs);
  $(id).parent().find('button').on('click', function(e) {
    e.preventDefault();
    $(id).append(inputs.clone());
    $(id).submit();
  });
<% end %>

此代码将 javascript 添加到表单表行,获取输入,将它们附加到 ID 并提交表单。preventDefault(); 防止在刷新页面并且表单实际工作时发送两次查询。

4

2 回答 2

6

Turbolinks

As mentioned, the problem with Turbolinks is that it reloads the <body> part of the DOM with an ajax call - meaning JS is not reloaded, as it's in the head

The typical way around this issue is to delegate your JS from the document, like this:

$(document).on("click", "#your_element", function() {
    //your code here
});

Because document is always going to be present, it will trigger the JS continuously


Remote

With your issue, it's slightly more tricky

The problem is you're relying on the JQuery UJS (unobtrusive JavaScript) engine of Rails, which is difficult to remedy on its own

We've never had this issue & we use Turbolinks all the time - so I suppose the problem could be with how you're constructing your form / handling the request. This GitHub seemed to recreate the issue, and it was to do with the table

Maybe you could try:

<%= form_for [object], remote: true do |f| %>                                                   
    <%= f.text_field :name, class: 'form-control' %>                                     
    <%= f.email_field :email, class: 'form-control' %>                              
    <%= f.submit button_name, class: 'btn btn-sm btn-primary' %>
<% end %>    
于 2014-03-09T13:02:07.033 回答
4

Turbolinks 不会完全重新加载您的页面,而只是其中的一部分。这就是它们如此快速的原因,但是如果您的 JavaScript 需要重新加载整个页面,您将遇到麻烦。它确实适用于刷新的原因是因为现在您强制页面完全重新加载。

编辑:这个宝石可能值得一试:https ://github.com/kossnocorp/jquery.turbolinks

有关 turbolinks 内部工作原理的一些额外信息:http: //guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks

或者:https ://github.com/rails/turbolinks

Ps 还要确保 javascript_include_tag 在 head 标签内(而不是在 body 中)

于 2014-03-09T12:44:48.180 回答