respond to js

Can someone tell me how this works, I just don’t understand what’s going on here

_form.html.erb

<%= form_for [post, comment], remote: true,

html: {

class: “new_blog_comment”, id: “new_blog_comment” } do |f| -%>

<%=t :leave_a_comment, scope: 'blogit.comments'%>

<%= field do %>

<%= f.label :body, t(:your_comment, scope: ‘blogit.comments’) %>

<%= f.text_area :body %>

<%= errors_on(comment, :body) %>

<% end %>

<%= actions do %>

<%= f.submit t(:add_comment, scope: ‘blogit.comments’), :disable_with => t(:adding_comment, scope: ‘blogit.comments’) %>

<% end %>

<% end -%>

before_action :find_commentable, only: :create

def create

commentable = commentable_type.constantize.find(commentable_id)

@comment = Comment.build_from(commentable, current_user.id, body)

user_id = commentable.user_id

respond_to do |format|

if @comment.save

make_child_comment

format.html { redirect_to("/page/#{user_id}", :notice => ‘Comment was successfully added.’) }

else

format.html { render :action => “new” }

end

end

end

def find_commentable

@commentable_type = params[:commentable_type].classify

@commentable = @commentable_type.constantize.find(params[:commentable_id])

end

create.js.erb

var $form = $(“form#new_blog_comment”);

<% if @comment.save %>

$("#comments").append("<%= escape_javascript(render(@comment)) %>");

$form.get(0).reset();

<% else %>

$form.html("<%= escape_javascript(render(‘form’)) %>");

<% end %>

Does it work?

In a nut shell.
The comment is submitted via JavaScript, aka Ajax, and the controller will do what it needs to do. It appears that it will only responded to html not Ajax.

But if it did.
It should render the .js.erb and depending on if the comment was saved it will append the comment to the page. If it fails the form is displayed.