为什么 rails 有嵌套资源?

why do rails have nested resources?

学习 rails 并在 routes.rb

中发现了这个嵌套资源
resources :posts do
    resources :comments
end

鉴于 post 和评论之间存在关联(一个 post 有很多评论,一个评论属于一个 post),我可以看出这种关联在上面的代码中以类似的方式

但是为什么我们需要嵌套资源而不是简单地声明

resources :posts
resources :commments

两者在某些方面是否相同?

假设您想让您的用户导航到:

# GET
http://yoursite.com/posts/1/comments

这将允许您查看与 ID 为 1 的 post 关联的评论列表。

您需要使用以下内容来执行此操作:

resources :posts do
    resources :comments
end

但是,如果您有以下路线:

resources :posts
resources :commments

你必须传递一个参数,它看起来像:

# Get
http://yoursite.com/comments/?post=1

第一种方法更简单、更整洁!

更新:

您可以在 the Rails manual. There's also a specific section for nested resources.

上阅读有关路由的堆

对于关联,建议使用嵌套路由。拥有在逻辑上是其他资源的子资源的资源是很常见的。例如,假设您的应用程序包括这些模型:

class Magazine < ActiveRecord::Base
  has_many :ads
end

class Ad < ActiveRecord::Base
  belongs_to :magazine
end

嵌套路由允许您在路由中捕获这种关系。在这种情况下,您可以包含此路由声明:

resources :magazines do
  resources :ads
end

然后 获取

/magazines/:magazine_id/ads

显示特定杂志的所有广告列表