问题描述
在开始编写任何代码之前,我正在为我的 REST API 构建 URL.Rails REST 魔法很棒,但我对 URL 的格式有些困扰,例如:
I'm working on building the URLs for my REST API before I begin writing any code. Rails REST magic is fantastic, but I'm slightly bothered the formatting of a URL such as:
http://myproject/projects/5
其中 Project 是我的资源,5 是 project_id.我认为如果用户希望检索他们所有的项目,那么相应的 HTTP GET http://myproject/projects
是有意义的.但是,如果他们希望检索有关单一资源(例如项目)的信息,那么使用 http://myproject/project/5
与 http://myproject/projects/5
.最好避免这种头痛,或者你们中的一些人是否有类似的担忧,甚至更好 - 有一个可行的解决方案?
where Project is my resource and 5 is the project_id. I think if a user is looking to retrieve all of their projects, then a respective HTTP GET http://myproject/projects
makes sense. However if they're looking to retrieve information on a singular resource, such as a project, then it makes sense to have http://myproject/project/5
vs http://myproject/projects/5
. Is it best to avoid this headache, or do some of you share a similar concern and even better - have a working solution?
推荐答案
Rails (3) 在单数与复数问题上有很多约定.例如,模型类总是单数(Person
),而对应的表总是复数(people
).(例如,Person.all
映射到 select * from people
.)
Rails (3) has a lot of conventions when it comes to singular vs plural. For example, model classes are always singular (Person
), while the corresponding tables are always plural (people
). (For example, Person.all
maps to select * from people
.)
对于路由,有单数资源和复数资源的概念.所以如果你做了 resource :account
那么你会得到像 /account
这样的路径作为默认路径或 /account/edit
作为一个路径用于编辑帐户的表单.(请注意,Rails 使用 /account
和 PUT
方法来实际更新帐户./account/edit
是一种用于编辑帐户的表单,这是与帐户本身不同的资源.)但是,如果您执行了 resources :people
,那么您将获得类似 /people
、/people/1 的路径
和 /people/1/edit
.路径本身指示给定类型的资源是否只能有一个实例,或者是否可以有多个实例由某种类型的标识符区分.
For routes, there's a concept of a singular resource as well as a plural resource. So if you did resource :account
then you would get paths like /account
for the default path or /account/edit
for a path to a form to edit the account. (Note that Rails uses /account
with a PUT
method to actually update the account. /account/edit
is a form to edit the account, which is a separate resource from the account itself.) If you did resources :people
, however, then you would get paths like /people
, /people/1
, and /people/1/edit
. The paths themselves indicate whether there can only be one instance of a given type of resource, or whether there can be multiple instances distinguished by some type of identifier.
这篇关于Ruby on Rails - 在 REST API 中区分复数资源和单数资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!