2012-03-15 96 views
2

我在用戶頁面上有基於ajax的微博評論。它有效,但不正確。當我向任何微博提交新評論時,它總是張貼到最後微博。然後,如果我通過「F5」刷新頁面,則所有內容都會到位 - 新評論位於正確的微博中。提前致謝。基於Ajax微博的評論(Ruby on Rails)

comment.rb

class Comment < ActiveRecord::Base 
    attr_accessible :comment_content 
    belongs_to :user 
    belongs_to :micropost 
end 

comments_controller.rb

class CommentsController < ApplicationController 
    before_filter :signed_in_user, only: [:create, :destroy] 

    def create 
    @micropost = Micropost.find(params[:micropost_id]) 
    @comment = Comment.new(params[:comment]) 
    @comment.micropost = @micropost 
    @comment.user = current_user 
     respond_to do |format| 
     @comment.save 
      format.html { redirect_to current_user } 
      format.js 
     end 
    end 
end 

_micropost.html.erb

<tr> 
    <td class="micropost"> 
    <span class="content"><%= wrap(micropost.content) %></span> 
    <span class="timestamp"> 
    Posted <%= time_ago_in_words(micropost.created_at) %> ago. 
    </span> 
    <%= render 'shared/comment_form', micropost: micropost %> 
    <div id="comments"> 
    <%= render micropost.comments %> 
    </div> 
    </td> 
</tr> 

_comment_form.html.erb

<%= form_for ([micropost, @comment]), :remote => true do |f| %> 
<%= render 'shared/error_messages', object: f.object %> 
<%= f.text_area :comment_content, :size => "40x2" %> 
    <button class="btn" type="submit"> 
    Comment 
    </button> 
<% end %> 

_comment.html.erb

<span style="width: 100%; background:#dff0d8"><%= wrap(comment.comment_content) %></span> 
<span class="timestamp"> 
Posted by <%= comment.user.name %> <%= time_ago_in_words(comment.created_at) %> ago. 
</span> 

create.js.erb

$('#comments').html("<%= escape_javascript(render(:partial => @micropost.comments)) %>"); 
+0

我不明白你的問題。你有一些錯誤嗎? – shingara 2012-03-15 09:02:48

+0

沒有錯誤,但評論只發布到最後一個微博。 – Bennington 2012-03-15 09:11:55

+0

如果您的視圖調用您的JS如何? – shingara 2012-03-15 09:16:01

回答

0

也許你可以改變

@comment = Comment.new(params[:comment]) 
@comment.micropost = @micropost 

@comment = @micropost.comments.build(params[:comment]) 
+0

謝謝,但也有同樣的問題。 – Bennington 2012-03-15 09:31:58