使用嵌套资源时发生路由错误

时间:2012-09-13 19:35:27

标签: ruby-on-rails routing nested-resources

我有一个帖子和评论模型。注释属于Post,它嵌套在Post中的路径中。评论从帖子#show发布。我的路线看起来像这样:

  resources :posts do
    resources :comments, only: [:create, :edit, :update, :destroy]
  end

如果用户提交的评论未通过验证,则网址将如下所示:

app.com/posts/:id/comments

如果出于任何原因,用户决定在地址栏中按Enter键,则会出现路由错误:

Routing Error
No route matches [GET] "/posts/21/comments"
Try running rake routes for more information on available routes.

这让我觉得有些奇怪。我理解错误发生的原因,但似乎对可用性不是一个好主意。有没有办法防止这种情况发生?

在进行友好重定向时,这会成为一个更大的问题。当友好的重定向发生时,Rails将使用GET请求重定向到同一个URL,再次导致路由错误。

3 个答案:

答案 0 :(得分:1)

我认为避免它的最佳方法是为此案例创建一个路由,并重定向到适合您的应用程序的任何地方。如下所示:

match "/posts/:id/comments" => redirect {|params| "/posts/#{params[:id]}" }

而不是该路由错误,用户将被重定向到帖子页。

答案 1 :(得分:1)

如果您的路线是

resources :posts do
  resources :comments, only: [:create, :edit, :update, :destroy]
end

然后编辑的URL将是

app.com/posts/:post_id/comments/:id/edit

其中:id是评论。如果验证失败,您应该重定向回此URL。

def update
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])

  if @comment.update_attributes(params[:comment])
    redirect_to(edit_post_path(@post))
  else
    redirect_to(edit_post_comment_path(@post, @comment), :notice => "update failed")
  end
end

更好,因为您已经在正确的编辑网址

...
  else
    flash[:error] = "Error - could not update comment"
    render :action => "edit"
  end

答案 2 :(得分:0)

不是最好的,但另一个解决方案可能是通过帖子的嵌套属性添加评论。

相关问题