I'm creating a "without refresh page comment" using Jquery and Ajax.
Inside posts/show.html.erb
<%= @post.title %>
<%= @post.body %>
<%= render 'comment %>
posts/_comment.html.erb
<%= link_to "Add Comment", new_post_comment_path(@post), id: "new_comment", remote: true %>
<div id="comments">
<%= nested_comments @post.comments.arrange(:order => "created_at DESC") %>
</div>
comments.controller.rb
def create
@comment = @post.comments.new(comment_params)
@comment.user = current_user
@comment.save
respond_to do |format|
if @comment.save
format.html { redirect_to :back }
format.js
else
format.html { render action: "new" }
format.js
end
end
end
comments/_form.html.erb
<div id="comment_form">
<%= simple_form_for [@post, @comment], remote: true do |f| %>
<%= f.hidden_field :parent_id %>
<%= f.text_area :body %>
<br>
<%= f.submit "Confirm" %>
<% end %>
</div>
comments/new.js.erb
$('#new_comment').hide().after('<%= j render("form") %>');
comments/create.js.erb
$('#comment_form').remove();
$('#new_comment').show();
$('#comments').append('<%= j render(@comment) %>');
Everything work great. comment has appeared with no refresh page needed.
But i got one thing i didnt want, everytime i post a new comment, the comment went to the bottom of comment list (which i order the comment by created at DESC). I need to refresh the page to make all comments appear properly. I wish everytime i posted a new comment, it would be at the top of comment list. How to make it happen ? Thank You very much..
I assume this will resolve your problem.
The
.prepend()
method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use.append()
).