【发布时间】:2016-09-01 13:20:46
【问题描述】:
鉴于 RESTful API 中嵌套资源的以下 URL 设计:
/magazines/:magazine_id/ads/:id POST
考虑到广告 ID 可以唯一地识别杂志中的广告,在其中包含杂志 ID 的原因是什么?
此外,当向用户展示该 URL 或简单的约定时,它看起来可能会更好。有没有更深层次的含义或约束?
【问题讨论】:
标签: ruby-on-rails ruby rest url restful-url
鉴于 RESTful API 中嵌套资源的以下 URL 设计:
/magazines/:magazine_id/ads/:id POST
考虑到广告 ID 可以唯一地识别杂志中的广告,在其中包含杂志 ID 的原因是什么?
此外,当向用户展示该 URL 或简单的约定时,它看起来可能会更好。有没有更深层次的含义或约束?
【问题讨论】:
标签: ruby-on-rails ruby rest url restful-url
嗯,这在很大程度上取决于谁在开发。理论上,没有必要。
事实上,Rails Guides 在2.7.2 Section (Shallow Nesting) 中显示了这一点,您只能在资源没有 id 时嵌套资源:
resources :articles do
resources :comments, only: [:index, :new, :create]
end
resources :comments, only: [:show, :edit, :update, :destroy]
或者在你的情况下:
resources :magazines do
resources :ads, only: [:index, :new, :create]
end
resources :ads, only: [:show, :edit, :update, :destroy]
【讨论】:
鉴于广告 ID 可以唯一地标识跨杂志的广告?
这是最常见的约定,但不是通用的。您可以随意覆盖模型中的 to_param 并违反 Universality-by-database-primary-key 约定。想象一下,您也为杂志这样做(例如,出于 SEO 目的)。在这种情况下,在路线中包含弹匣 ID/slug 可能是非常必要的。
【讨论】:
这正是“浅”的作用:
resources :magazines do
resources :ads, shallow: true
end
意思完全一样
resources :magazines do
resources :ads, only: [:index, :new, :create]
end
resources :ads, only: [:show, :edit, :update, :destroy]
请参阅http://edgeguides.rubyonrails.org/routing.html 中的第 2.7.2 节浅嵌套
【讨论】: