respond to js

10 views
Skip to first unread message

fugee ohu

unread,
Feb 9, 2018, 9:00:23 PM2/9/18
to Ruby on Rails: Talk
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| -%>

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

  <%= field do %>
    <%= f.label :body, t(:your_comment, scope: 'blogit.comments') %><br>
    <%= f.text_area :body %><br>
    <%= 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 %>

John Ivanoff

unread,
Feb 10, 2018, 1:04:55 PM2/10/18
to Ruby on Rails: Talk
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.

Reply all
Reply to author
Forward
0 new messages