Why does this ajax request replace all my comments with the newly submitted comment?
So I have this form which requests a JS call when a comment is submitted:
<%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %>
<%= f.association :comment_title, :collection => @video.comment_titles, :label => "Comment Title:", :include_blank => false %>
<%= f.input :body, :label => false, :placeholder => "Post a comment." %>
<%= f.button :submit, :value => "Post" %>
<% end %>
It calls this create action in the comments controller:
def create
@comment = @video.comments.new(params[:comment].merge({:user_id => current_user.id}))
if @comment.save
respond_to do |format|
format.html { redirect_to :back }
开发者_开发知识库 format.js
end
else
respond_to do |format|
format.html { redirect_to :back, :alert => "Unable to add comment." }
format.js { render 'fail_create.js.erb' }
end
end
end
which renders this create.js.erb file:
$(".comment_content").html('<%= escape_javascript(render(@comment)) %>');
$(".comment_form")[0].reset();
The above create.js.erb file renders the comment partial into this file:
<% comment_title.comments.each do |comment| %>
<div class="comment_content">
<%= render comment %>
</div>
<% end %>
Why are all of my comments being replaced by the newly submitted comment in this AJAX request?
Here's my comment partial:
<%= link_to image_tag(comment.user.profile.photo.url(:tiny)), profile_path(comment.user.profile), :class => "comment_image" %>
<div class="textual_comment_content">
<div class="comment_text">
<span class="name_link">
<%= link_to "#{comment.user.name}", profile_path(comment.user.profile), :class => "normal" %>
</span>
<%= comment.body.gsub("'",''').html_safe %>
</div>
<span class="comment_footer">
<ul>
<li class="list_style"><%= time_ago_in_words(comment.created_at) %> ago</li>
<% unless current_user != comment.user %>
<li><%= link_to "Delete", video_comment_path(:video_id => @video, :id => comment), :method => :delete, :class => "normal" %></li>
<% end %>
</ul>
</span>
</div>
first You need to move wrapping div from first code to the partial:
<div class="comment_content">
</div>
then just insert html before/after first/last element:
$(".comment_content:first").before('<%= escape_javascript(render(@comment)) %>');
$(".comment_content:last").after('<%= escape_javascript(render(@comment)) %>');
精彩评论