编辑属于帖子的评论

时间:2013-12-30 20:21:35

标签: ruby-on-rails ruby-on-rails-4

所以我创建了一个博客,用户可以创建帖子,其他人可以评论该帖子。

我希望用户能够编辑评论。

到目前为止我所做的是以下内容:

我的路线是这样的:

  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

在我的视图文件中我使用了这显然是错误的

  <%= link_to 'Edit Comment', edit_post_comment_path(@comment) %>

我的控制器是这样的:

  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]

这是我第一次使用嵌套路线。我阅读了一些教程,但没有任何帮助我解决这个问题。我不知道怎么能通过这些钥匙...

(如果您需要任何其他信息,请告诉我,我会提供给他们)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

您需要同时传递@post@comment实例。

edit_post_comment_path(@post, @comment)

一般来说,您需要传递与路由所属资源匹配的每个实例。所以,在像

这样的单一路线中
edit_post_path(@post)

你只传递帖子。在post / comment嵌套路由中,您都会传递它们。在帖子/评论/你需要传递三种资源等等。

相关问题