ruby-on-rails - 编辑属于帖子的评论

标签 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

在我的 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/

相关文章:

ruby-on-rails - ActionDispatch::HostAuthorization::DefaultResponseApp 被阻止的主机:xxxxxx.herokuapp.com

ruby-on-rails - 如何在 Rails 中停止样式表自动链接?

ruby-on-rails - 我怎样才能以 ruby 开始当前的工作日?

ruby-on-rails - 仅在生产环境中使用异步 JavaScript?

ruby-on-rails - 具有连接和顺序的不同记录

ruby-on-rails - Nokogiri gem 安装在 Capistrano 部署中失败

ios - 在 Nitrous.io 上修复 Rails 和服务器

ruby-on-rails - 为 Rails 4 中的特定 Controller 重定向记录器输出

ruby-on-rails - 使用 Ruby on Rails 的 Postgres 公用表表达式查询

ruby-on-rails - 使用 sqlite 在 rails 4 中存储数组