Reputation: 181
I want to make comment form with Ajax call.
# app/views/comments/index.html.erb
<div id="comment_section">
<%= render @comments %>
</div>
<%= form_for(@comment, remote: true) do |f| %>
<%= f.input :contents %>
<%= f.submit %>
# app/vies/comments/_comment.html.erb
<p><%= comment.content %></p>
# app/controllers/comments_controller.rb
def create
@comment = Comment.create(comment_params)
respond_to do |format|
format.js
end
end
# app/views/comments/create.js.erb
$("#new_comment").bind("ajax:success", function(){
$("#comment_section").prepend("<%= j render 'comment', locals: { comment: @comment } %>");
});
I thought it is very simple and there is no chance to have any errors. When I submit the form for the first time(e.g. contents = "a"), it makes no error and just one comment is prepended in the comment_section. But when I submit forms after that(e.g. contents = "b" , contents = "c"), it always prepend comments which was created before.
What is going on? Log just says there was just one query and one render for new comment. After refreshing the page, it appears right.
What am I missing? I don't know jQuery and Ajax well so I doubted turbolink could make some errors for this.(just my own guess) Any comments will be a huge help for me, thanks!
Upvotes: 1
Views: 117
Reputation: 1849
you're probably getting duplicate calls to the binded event. (add a console log to check)
There's no need to bind an ajax:success event. (try to understand why you even inserted that because you do not need to). Your remote .js will go to that "create.js.erb code" so try removing the binded event and just use the $().prepend line of code by itself.
Upvotes: 4