在页面刷新时显示重复注释(在初始AJAX追加之后)[Rails]

时间:2016-11-17 01:53:43

标签: ruby-on-rails ajax duplicates refresh

似乎无法想出这个...在我的rails应用程序中,我有Post和Comment资源。创建新注释时,我想使用AJAX重新加载注释列表。该部分似乎工作正常 - 但是,当随后重新加载整个页面时,该列表还会显示注释的副本,如此screenshot所示。关于可能导致这种情况的任何想法?

(注意:删除其中一条评论也会删除副本)

  

视图/用户/ show.html.haml

object MyNumber {
    // This does not depend on any instance of MyNumber
    def add(c: Int, b: Int): Int = c + b
}
class MyNumber(a: Int) {
    // This depends on an instance of MyNumber
    def next: Int = a + 1
}
  

视图/评论/ _comment.html.haml

= form_for([post, post.comments.build], remote: true) do |f|
  = f.text_field :content, placeholder: 'Press ENTER to submit...', class: "comment_content", id: "comment_content_#{post.id}"
    - if post.comments
      .comments{ id: "comments_#{post.id}" }
        - post.comments.each do |comment|
          = render post.comments, post: post
  

控制器/ comments_controller.rb

- unless comment.content == nil
  .comment{ id: "comment_#{comment.id}" }
    .user-name
      = link_to comment.user.identities.first.nickname, comment.user
    .comment-content
      = comment.content
        - if comment.user == current_user
          = link_to post_comment_path(post, comment), data: { confirm: "Are you sure?" }, method: :delete, remote: true do
            %i.fa.fa-close
  

视图/评论/ create.js.erb

class CommentsController < ApplicationController
  before_action :set_post

    def create  
      @comment = @post.comments.build(comment_params)
      @comment.user_id = current_user.id

      if @comment.save
        respond_to do |format|
          format.html { redirect_to :back }
          format.js
        end
      else
        render root_path
      end
    end

  ...

更新

按照@ uzaif的建议,我用“.html”替换了“.append”。只有当我还将代码移出_comment部分时,这才解决了这个问题。这不是一个理想的解决方案......我仍然想知道是否/如何解决问题并保持我个人的评论不完整。

0 个答案:

没有答案