[英]Ajax based micropost's comments (Ruby on Rails)
I have ajax based micropost's comments on the user page. 我在用户页面上有基于Ajax的micropost的评论。 It works, but not correctly.
它有效,但不能正确执行。 When I submit a new comment to any micropost, it always posts to the last micropost.
当我向任何微博提交新评论时,它总是发布到最后一个微博。 Then, if I refresh the page by "F5", everything falls into place - the new comment is in the correct micropost.
然后,如果我按“ F5”刷新页面,则所有内容都就位了-新评论位于正确的微博中。 Thanks in advance.
提前致谢。
comment.rb comment.rb
class Comment < ActiveRecord::Base
attr_accessible :comment_content
belongs_to :user
belongs_to :micropost
end
comments_controller.rb 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 _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 _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 _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 create.js.erb
$('#comments').html("<%= escape_javascript(render(:partial => @micropost.comments)) %>");
Maybe you can change 也许你可以改变
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
to 至
@comment = @micropost.comments.build(params[:comment])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.