Add Comments + Ajax

I started to study rails and I would like to add ajax to the comments

Comments must be added using Ajax

Could you help or link to an example?

Here if my config.rb is:

  resources :posts do
    resources :comments
  end

in post / show.html.erb

<p><%= @post.title %></p>

    <h2>Comments:</h2>
    <div id='com'>
      <%= render @post.comments %>
    </div>

<h2>Add a comment:</h2>
<%= render "comments/form" %>

in view / comments / _comment.html.erb:

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>
<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>
<%= link_to "Del", [comment.post, comment], :confirm => 'Are you sure?', :method => :delete %>
<hr>

in the comments /form.html.erb

<%= form_for([@post, @post.comments.build], remote: true) do |f| %>
.
.
.

in comment_controller:

class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])

    respond_to do |format|
        format.html { redirect_to post_path(@post) }
        format.js 
    end
  end

and add file: _create.js.erb

$('#com').html("<%=j render @post.comments %>");

without remote true everything works (but reloads the page) the action removes work on

in application.html.erb

  <%= javascript_include_tag 'application' %>

when I click the button to submit the form - nothing happens

but when I (after sending) reload the page - I saw the added comment (s)

+5
source share
2 answers

You need to enable unobtrusive javascript

in app/assets/javascripts/application.js

You have it (if not add it)

//= require jquery
//= require jquery_ujs

and

@DemitriyDN:)

_create.js.erb create.js.erb

+3

comment_controller:

class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])

    respond_to do |format|
        format.html { redirect_to post_path(@post) }
        format.js 
    end
  end
end
0

All Articles