为什么link_to提交表单两次?

时间:2016-09-05 09:55:41

标签: javascript jquery ruby-on-rails ruby ruby-on-rails-4

我正在尝试在rails中使用JavaScript和jquery来更新div而不重新加载页面。它的工作,但评论正在创建两次。我知道部分形式有问题,但无法弄清楚。有帮助吗?

以下是文件 -

_new_comment.html.erb

<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %>

    <div>
        <%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %>

        <%= f.hidden_field :post_id, :value => post.id %>

        <span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span>
    </div>

<% end %>

comments_controller.rb

def create
    @comment = Comment.new(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
        flash[:notice] = 'Comment added sucessfully'
        respond_to do |format|
            format.html { redirect_to home_posts_url }
            format.js
        end
    end
end

create.js.erb

$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>');
$("#comment-new-83")[0].reset();

home.js

jQuery.ajaxSetup({
    'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

$(document).ready(function() {
    $("#comment-new-83").submit(function() {
        $.post($(this).attr("action"), $(this).serialize(), null, "script");
        return false;
    })
})

1 个答案:

答案 0 :(得分:0)

<script id="firstTemplate" type="text/x-handlebars-template"> <ul> \{{#lines}} <li>\{{name}}</li> \{{/lines}} </ul> </script> 会自动发布到控制器。您无需使用jquery显式提交表单。

Reference