Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - Rails 4 Turbolinks make form submit multiple times

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:

view:

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"

controller:

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

and 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 %>

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

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

thanks in advs

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...