Search code examples
javascriptjqueryruby-on-railsruby-on-rails-3jrails

In my comment app when i refresh the page comments disappears


My comment app works ,but the only problem is whenever i refresh the page the comments disappear.In the log it shows the body is inserted in the comments table(it is saved).What am i doing wrong here?Any help will be appreciated.Thank you in advance.

View#show

    <div id="comments"></div>

   <%= form_for :comment,:remote => true,:url=>  {:controller=>"comments",:action=>"create"},:html => { :id => 'new-comment'} do |f| %>
   <%= f.text_area(:body) %>
   <div class="errors"></div>
   <%= f.submit "post" %>
   <% end %>

Comment controller

    class CommentsController < ApplicationController
    respond_to  :js
   def create
   @deal=Deal.find(1)
   @comment [email protected](params[:comment])
   @comment.save
   respond_with( @comment, :layout => !request.xhr? )  
   end

    def show
    @comment=Comment.all
    @deal=Deal.find(1)
    @[email protected]
    end
   end

create.js.erb

     $('#comments').append("escape_javascript(@comment.body)");

Solution

  • I don't see where your comments are being display in your show template.

    How about something like this?

       <div id="comments">
          <% @comments do |comment| %>
            <%= comment.body %>
          <% end %>
       </div>
    
       <%= form_for :comment,:remote => true,:url=>  {:controller=>"comments",:action=>"create"},:html => { :id => 'new-comment'} do |f| %>
         <%= f.text_area(:body) %>
          <div class="errors"></div>
         <%= f.submit "post" %>
       <% end %>
    

    Note, you need to set @comments in the controller or use another method of getting comments, e.g. @view = View.find(params[:id]) and <%= @view.comments.each do |comment| %>...