因此,我创建了一个博客,用户可以在其中创建帖子,其他人可以对该帖子发表评论。
我希望用户能够编辑评论。
到目前为止我所做的如下:
我的路线是这样的:
resources :posts do
resources :comments
end
当我抓取路线时,我得到这个:
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
在我的 View 文件中我使用了这个,这显然是错误的
<%= link_to 'Edit Comment', edit_post_comment_path(@comment) %>
我的 Controller 是这样的:
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def update
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
if @comment.update(comments_params)
redirect_to post_path(@post)
else
render 'edit'
end
end
当我尝试访问(帖子的)页面时,出现此错误:
No route matches {:action=>"edit", :controller=>"comments", :id=>nil, :post_id=>nil, :format=>nil} missing required keys: [:post_id, :id]
这是我第一次处理嵌套路由。我读了一些教程,但没有什么能真正帮助我解决这个问题。我不知道如何传递这些 key ...
(如果您需要任何其他信息,请告诉我,我会提供)
非常感谢任何帮助!
最佳答案
您需要传递 @post
和 @comment
实例。
edit_post_comment_path(@post, @comment)
一般来说,您需要传递与路由所属资源匹配的每个实例。所以,在像这样的单一 route
edit_post_path(@post)
你只传递了帖子。在帖子/评论嵌套路由中,您可以同时传递两者。在帖子/评论/任何您需要传递三个资源等的内容中。
关于ruby-on-rails - 编辑属于帖子的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846885/