I currently have a comment section that posts only after the whole page refreshes. Although after the post the page refreshes by itself it feels inefficient for the whole page to refresh. I was wondering if anyone can help me with a js file that would refresh just that partial, I am still shakey with my js. Any help is much appreciated! Thank you!
This is my current js for the create.js:
$("#comments").html("<%= escape_javascript(render(:partial => @micropost.comments)) %>");
comment controller
class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
format.html
format.js
end
end
end
Comment Section
<div id='CommentContainer-<%= micropost.id%>' class='CommentContainer Condensed2'>
<div class='Comment'>
<%= render :partial => "comments/form", :locals => { :micropost => micropost } %>
</div>
<div id='comments'>
<%=render micropost.comments %>
</div>
</div>
You should use something like this in your controller. This will trigger both the js and html templates as needed.
This will then require views/comments/create.js to respond with something like:
And the view for the comments will be
index.html.erbNow all you have to do is set up a
matchfor/api/micropost/:id/commentsin your routes, and this can then serve the list of comments in the desired html format.Note that this is not completely restful, but I like to keep the
/apithere to distinguish calls coming from xhr on a url level.