Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add comments + Ajax

I've started learning rails and I would like to add ajax to comments

Comments should be added using Ajax

Can you please help or link to an example?

Here if my config.rb:

  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 comments/form.html.erb

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

in comments_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 in view add file : _create.js.erb

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

without remote true all works ( but reload page ) action delete works to

in application.html.erb

  <%= javascript_include_tag 'application' %>

when i click to submit form - nothing happens

but when i (after submit) reload page - i saw added comment(s)

like image 977
Dmytro Vasin Avatar asked Oct 22 '22 11:10

Dmytro Vasin


1 Answers

You need to include unobtrusive javascript

in app/assets/javascripts/application.js

Do you have this (if not add it )

//= require jquery
//= require jquery_ujs

and

Answered by @DemitriyDN himself :)

rename _create.js.erb to create.js.erb

like image 158
Pritesh Jain Avatar answered Oct 27 '22 10:10

Pritesh Jain