0

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 =@deal.comments.build(params[:comment])
   @comment.save
   respond_with( @comment, :layout => !request.xhr? )  
   end

    def show
    @comment=Comment.all
    @deal=Deal.find(1)
    @comment=@deal.comments
    end
   end

create.js.erb

     $('#comments').append("escape_javascript(@comment.body)");
katie
  • 2,921
  • 8
  • 34
  • 51

2 Answers2

1

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| %>...

Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
0

I guess the comment has a belongs_to relationship with the post that is not assigned.

In your form you should add

<%= f.hidden_field :post_id, @post.id %>

If you want to play by the book, post_id should be attr_protected and instead assign it manually in the comments controller

@comment = Comment.new(params[:comment])
@comment.post_id = params[:comment][:post_id]
@comment.save
bandito
  • 447
  • 2
  • 2
  • Yes that make sense but how is that related to the comment disappear after the page is refreshed? – katie Oct 11 '11 at 21:06
  • well I guess because you fetch comments by post id (@post.comments or Comment.where(:post_id => params[:id])) and since your newly created comment has a nil post_id, your comment disappears. – bandito Oct 11 '11 at 21:12
  • Above is the original code,suprisingly @comment=@deal.comments dont return an array as expected – katie Oct 11 '11 at 21:25