ruby-on-rails - Rails 中的嵌套路由是什么?

标签 ruby-on-rails routing routes nested-routes

我刚开始学习Rails,刚接触过嵌套路由。我正在查看的示例涉及博客文章和评论。我想了解嵌套路由在 Rails 中的好处。

据我所知,评论的嵌套路由中包含的所有信息,例如 /articles/:article_id/comments/:id(.:format) 都包含在评论中对象本身,因此它不会向 Action 传递额外信息。

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

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

谁能解释一下?

最佳答案

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

class Article< ActiveRecord::Base
  has_many :comments
end

class Comment< ActiveRecord::Base
  belongs_to :article
end

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

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

/articles/:article_id/comments/:id(.:format)

这是评论 Controller show action,这个路由允许你在 show action 中找到文章和你的评论

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

不仅仅是显示操作(您可以在其中使用一些其他逻辑来查找与该评论关联的文章)您需要为您的新操作嵌套路由,您必须在其中找到该文章然后构建评论对于那篇文章 之类的东西

def new
  @article = Article.new
  @comment = @article.comments.build
end

正如 @August 指出的那样,您可以通过使用浅嵌套来分离出您希望嵌套路由的操作,您可以这样做:

resources :articles do
  resources :comments, shallow: true
end

结帐 nested routes了解更多信息

关于ruby-on-rails - Rails 中的嵌套路由是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219534/

相关文章:

ruby-on-rails - 在不干扰 ruby​​ on rails 进程的情况下,在后台发送电子邮件的最佳方法是什么?

ruby-on-rails - 使用 capistrano 从 rails 3 升级到 rails 4,现在图像 Assets 不显示。为什么?

asp.net - 我可以从站点地图生成 ASP.NET MVC 路由吗?

Angular2 - 多个模块的共享布局

javascript - 如何使用自动表单和 Iron 路由器重定向到新页面?

Flutter 导航、所需参数、单独的路由文件、如何正确编码

angularjs - 具有深度嵌套路由的 Angular2 路由 v3.0.0

ruby-on-rails - 有没有办法在浏览器中显示 Rails 的日志文件?

ruby-on-rails - 如何在 Ruby on Rails 应用程序中为 SSL 客户端配置私钥

ruby-on-rails - 仅为本地主机创建 rails 路由