How to use ajax on rails 4?

I am trying to create a comment area in rails 4 using ajax. My target is to create comment and its output in same page without page loading. I have added some code. When i click on “add comment” button the data entered to DB, but does not reflect in same page.Please share with me if any one have any idea, thank u.

My codes are below:

In comment controller:

def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create
    @comment.body = params[:comment]["body"]

    respond_to do |format|
        format.html { redirect_to @article }

In show.html.erb under views/articles

<div class="col-xs-12 col-sm-12">
  <h2 class="text-center"><%= @article.title.html_safe %></h2>
    <p><%= @article.body.html_safe %></p>
        <div id="comments">
             <!--  <p><%= render :partial => @article.comments %></p> -->
             <%= render :partial => 'comments/comment', :collection => @article.comments %>
        <%= form_for([@article,], :remote => true) do |f| %>
                <%= f.label :body, "New comment" %><br/>
                <%= f.text_area :body, type:"text", tabindex: "6", class: "form-control",  placeholder: 'your comment', rows: "4", required: true  %>
              <p><%= f.submit "Add comment" %></p>
        <% end %>

_comment.html.erb under view/comments

<%= div_for comment do %>
                Posted <%= time_ago_in_words(comment.created_at) %> ago
        <%= comment.body %>

        <%= link_to 'Delete', article_comment_path(comment.article_id,, method: :Delete, :class => 'btn btn-sm btn-warning', tabindex: "3" %>

        <%= link_to 'Edit', article_path(comment.article_id,, :class => 'btn btn-sm btn-warning', tabindex: "3" %>                         


create.js.erb under views/comments

page.insert_html :bottom, :comments, :partial => 'comment', :object => @comment


config.action_view.JavaScript_expansions[:defaults] = %w(jquery rails application)

Source: ruby

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.