ruby-on-rails - 基于Ajax的微博评论(Ruby on Rails)

标签 ruby-on-rails ruby ajax comments

我在用户页面上有基于ajax 的微博评论。它有效,但不正确。当我向任何 微博提交新评论时,它总是发布到最后 微博。然后,如果我按“F5”刷新页面,一切就绪——新评论出现在正确的微博中。提前致谢。

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)) %>");

最佳答案

也许你可以改变

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

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

关于ruby-on-rails - 基于Ajax的微博评论(Ruby on Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9715506/

相关文章:

ruby-on-rails - 如何检查 Controller 中私有(private)方法的返回值

ruby-on-rails - Gem::安装错误

javascript - 带有包含表单的 Bootstrap 模态视图的 Rails 应用程序,提交和消失模态视图而无需重新加载页面

ruby - 为什么在 Array 已经是 Enumerable 时使用 Array#to_enum?

javascript - Flask - 在成功的 json 上通过 javascript 重定向

ruby-on-rails - rails/Rack : retrieving request params from within canonical_host middleware

ruby - 无法加载这样的文件 - toml-rb,尽管安装了 gem

ruby - 独立 ruby​​ 可执行文件中的命名空间 thor 命令

ajax - laravel 中未捕获的 TypeError : FormData constructor: Argument 1 does not implement interface HTMLFormElement.

javascript - 如何使用 jQuery.ajax 将此 JSON 转换为在 HTML 中显示,为什么最后是 0?