如何在rails中使用closure_treegem回复评论?

How to reply to comments using closure_tree gem in rails?

我是 ROR 的新手,在尝试创建嵌套评论时遇到了严重的问题。在我的应用程序中,用户可以创建一个 post (wad)。每个 wad 有很多评论,每个评论 belongs_to 只有一个 wad。我的资源嵌套如下:

resources :wads do
    member do
      put "like", to: "wads#upvote"
    end
    resources :comments
  end

我可以 post,编辑和删除评论,但是当我尝试回复时,出现 RecordNotFound 错误。该应用程序正在重新路由到不正确的页面,即 /wads/comment_id/comments/new,但我认为它应该重定向到 /wads/wad_id/comments/comment_id。这是我的评论控制器中的创建方法和新方法:

def create
        if params[:comment][:parent_id].to_i > 0
            parent = @wad.comments.find_by_id(params[:comment].delete(:parent_id))
            @comment = parent.children.build(comment_params)
            @comment.save
        else
            @comment = @wad.comments.create(params[:comment].permit(:content))
            @comment.user_id = current_user.id
            @comment.save
        end

        if @comment.save
            redirect_to wad_path(@wad)
        else
            render 'new'
        end
    end



    def new
        @comment = Comment.children.create(parent_id: params[:id])
        @comment.save
    end

这是我用来link回复的:<%= link_to "Reply", new_wad_comment_path(comment) %>

几天来我一直在仔细阅读 Whosebug 上类似问题的答案,但 none 的答案对我有用。有人可以帮我解决这个问题吗?

路线:

new_wad_comment GET    /wads/:wad_id/comments/new(.:format)      comments#new
       edit_wad_comment GET    /wads/:wad_id/comments/:id/edit(.:format) comments#edit
            wad_comment GET    /wads/:wad_id/comments/:id(.:format)      comments#show

find_comment方法:

def find_comment
    @comment = @wad.comments.find(params[:comment_id])  
end

评论模型:

class Comment < ApplicationRecord
  acts_as_tree order: 'created_at DESC'
  belongs_to :wad
  belongs_to :user
end

Wad 型号:

 class Wad < ApplicationRecord
      acts_as_votable
      belongs_to :user
      has_many :comments, dependent: :destroy
      default_scope -> { order(created_at: :desc) }
      validates :user_id, presence: true
      validates :category, presence: true
      validates :long_form, presence: true, length: { maximum: 1000 }
      validates :short_form, presence: true, length: { maximum: 140 }
      validates :problem_state, presence: true, length: { maximum: 50 }
    end

因为您使用的是嵌套路由,所以您必须在 link_to 调用中将 wad 与评论一起传递。像这样:

<%= link_to "Reply", new_wad_comment_path(wad, comment) %>

link_to 中的 wad 将为您的路线提供它正在寻找的 wad_id。