Rails 中的嵌套路由有什么作用?

Cu1*_*ure 3 routes ruby-on-rails nested-routes

我是 Rails 的新手,刚刚遇到了嵌套路由。我正在查看的示例涉及博客文章和评论。我试图了解 Rails 中嵌套路由的好处。

据我所知,注释的嵌套路由中包含的所有信息(例如/articles/:article_id/comments/:id(.:format)全部包含在注释对象本身中),因此它不会向操作传达附加信息。

为什么不只使用非嵌套路由,例如/comments/:id(.:format)

使用嵌套路由显然有一个很好的理由,但我一直无法解决。到目前为止,我能看到的唯一好处是,在阅读 URL 时,它可以更好地说明文章和评论之间的关系,但所有这些信息无论如何都包含在评论对象中。

有人可以解释一下吗?

Man*_*eep 5

在您的模型中,您将设置此关联

class Article< ActiveRecord::Base
  has_many :comments
end

class Comment< ActiveRecord::Base
  belongs_to :article
end
Run Code Online (Sandbox Code Playgroud)

因此,每个评论都与一篇文章相关联,您需要一些逻辑来找到评论对应的文章

这就是嵌套路由的用武之地,它可以让您在控制器操作中找到该评论的文章。如果你再看那条路线

/articles/:article_id/comments/:id(.:format)
Run Code Online (Sandbox Code Playgroud)

这是评论控制器显示操作,此路线允许您在显示操作中找到文章和评论

def show
  @article = Article.find(params[:article_id])
  @comment = Comment.find(params[:id])
  # if you are not using nested routes then you can find out associated article by
  @article = @comment.article # but you'll have to query your database to get it which you can simply find if you are using nested route
end
Run Code Online (Sandbox Code Playgroud)

除了显示操作(您可以使用一些其他逻辑来查找与该评论相关的文章)之外,您还需要为新操作嵌套路由,您必须找到该文章,然后通过类似的方式为该文章构建评论

def new
  @article = Article.new
  @comment = @article.comments.build
end
Run Code Online (Sandbox Code Playgroud)

正如所@August指出的,您可以使用浅层嵌套来分离出您希望嵌套路由的操作,您可以执行以下操作:

resources :articles do
  resources :comments, shallow: true
end
Run Code Online (Sandbox Code Playgroud)

结账nested routes了解更多信息