Rails 4 Turbolinks使表单多次提交 [英] Rails 4 Turbolinks make form submit multiple times

查看:169
本文介绍了Rails 4 Turbolinks使表单多次提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一些代码在Rails 3上工作得很好但不在Rails 4上,我猜它是由Turbolinks引起但我不太了解它,不能深入挖掘来解决我的问题,这里是代码:

I use some code working nicely on Rails 3 but not on Rails 4, I guess it is caused by Turbolinks but I don't know much about it, can't dig more deep to solve my problem, here is the code:

查看:

a/v/m/_new_comment.slim                                                                                                                             
.new-comment                                                                                                                                         
- if current_user
  = render "editor_toolbar"
  = form_for(Comment.new, :remote => true, :url => mission_comments_path(@mission)) do |f|
  = f.text_area :content, :class => "span10",
    :rows => "4", :tabindex => "1"
  #preview.hidden
    = "Loading..." 
  = f.submit t("missions.submit_comment"),
    "data-disable-with" => t("missions.submitting"),
    :class => "btn btn-primary", :tabindex => "2"
- else
  = render "need_login_to_comment"

控制器:

def create
  @mission = Mission.find(params[:mission_id])
  @comment = @mission.comments.build(comment_params)
  @comment.user = current_user

  if @comment.save
  @mission.events.create(user: current_user, action: "comment")
  render layout: false
end

和js:

<% if @comment.errors.any? %>                                                                                                                        
  $(".new-comment textarea").focus();
<% else %>
  $(".comments").append("<%= j (render @comment, :index => @mission.comments.count-1) %>");
  $(".new-comment #preview").addClass("hidden").html('');
  $(".new-comment textarea").css("display", "block").val('');
  $(".editor-toolbar .preview").removeClass("active");
  $(".editor-toolbar .edit").addClass("active");
<% end %>

我对这段代码有两个疑问,首先:这样的控制器代码不起作用
js代码转移到客户端但没有运行,我必须在该操作的底部添加渲染布局:false ,在Rails 3上不需要这个

I have two question about this code, first: the controller code like this isn't work the js code is transfer to client but not run, I have to add render layout: false at bottom of that action, no need this on Rails 3

第二个问题:当我第一次访问此页面时,重新加载页面,评论功能有效,但如果我点击其他页面的链接跳转到此页面,我提交此表单将导致多次ajax请求调用,将创建多个注释

second question: when I first visit this page, reload the page, comment function works, but if I click a link from other pages to jump to this page, I submit this form will cause ajax request call multiple times, multiple comments will be created

感谢advs

推荐答案

通过移动 = javascript_include_tagapplication,data-turbolinks-track=>解决了这个问题。真的从身体到头部,谢谢你所有的帮助

Solved this by moving = javascript_include_tag "application", "data-turbolinks-track" => true from body to head, thanks all your help

这篇关于Rails 4 Turbolinks使表单多次提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆