我是ROR的新手,并且在尝试创建嵌套注释时遇到了严重问题。在我的应用程序中,用户可以创建帖子(wad)。每一团都有很多评论,每个评论都只属于一团。我的资源嵌套如下:
resources :wads do
member do
put "like", to: "wads#upvote"
end
resources :comments
end
我可以发布,编辑和删除评论,但是当我尝试回复时,我收到了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_to "Reply", new_wad_comment_path(comment) %>
我已经仔细研究了stackoverflow上类似问题的答案,但是没有一个答案对我有用。有人可以帮我解决这个问题。
路线:
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 Model:
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
答案 0 :(得分:0)
因为您使用的是嵌套路线,所以您必须将此一起传递给您在link_to调用中的注释。像这样:
<%= link_to "Reply", new_wad_comment_path(wad, comment) %>
link_ to中的wad会为你的路线提供它正在寻找的wad_id。