开发者

In my comment app when i refresh the page comments disappears

My comment app works ,but the only problem is wh开发者_如何学JAVAenever 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)");


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜