在用户的页面上有微博。他们中的每一个都有评论形式。AJAX发布了评论。创建后,评论必须出现在使用评论形式的微博下面,但出于某种原因,评论总是出现在最后一个微博下面。
在DB中有所有的OK -在创建注释之后,我有下一个正确的信息:micropost_id,user_id,comment_id.,所以在刷新页面之后,所有的注释都在正确的位置上。
我该怎么做才能让评论贴在正确的微博上而不让人耳目一新?
comment.rb
class Comment < ActiveRecord::Base
attr_accessible :comment_content
belongs_to :user
belongs_to :micropost
endcomments_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)) %>");发布于 2012-09-26 08:38:18
首先,不要多次使用ID (#comments)。在整个页面上,ID应该是唯一的。我会尝试更改_micropost.html.erb以使用:
<div id="<%= dom_id(micropost) %>">
<%= render micropost.comments %>
</div>然后将create.js.erb更改为
$('#<%= dom_id(@micropost) %>').html("<%= escape_javascript(render(:partial => @micropost.comments)) %>");发布于 2012-09-26 06:27:04
尝试create.js.erb文件中的以下代码:
$('#comments_<%=@micropost.id%>:last').append("<div><span style='width: 100%; background:#dff0d8; font-size: 12pt' ><%= wrap(@comment.comment_content) %></span><br> <span class='timestamp' style='width: 100%; background:#dff0d8; font-size: 10pt'> Posted by<%= @comment.user.name %> <%= time_ago_in_words(@comment.created_at) %> ago.</span> </div>")看到你知道发生了什么,评论只不过是不同微博评论的一个id。
因此,浏览器不知道在哪里添加注释,无论是在第一个微博的注释中,还是在最后一个,所以您必须为div注释创建动态id。这就是我在上述例子中所做的。
另外,尝试在firefox中运行您的代码并使用firebug检查它。
发布于 2012-09-26 06:58:44
在create.js.erb中尝试
$(this).parent().find('#comments').html("<%= escape_javascript(render(:partial => @micropost.comments)) %>");或者更好的是,把新的评论放在前面
$(this).parent().find('#comments').prepend("<%= escape_javascript(render 'comments/comment', :comment => @comment) %>");https://stackoverflow.com/questions/9751882
复制相似问题