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.
1st time(submit content = "a")
- a(in the comment_section)
2nd time(submit content = "b")
- b
- a(I don't know why it appears)
- a(first created one)
3rd time(submit content = "c")
- c
- b(it occurs again)
- a(it occurs again)
- b(second)
- a(second)
- a(first one)
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.
After refresh
- c
- b
- a
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!