Rya*_*yan 4 ruby api rest url ruby-on-rails
我正在构建一个博客平台(RoR),并计划使用以下格式,任何缺点?
# All Users:
http://www.example.com/users/
# A single user (123 is the user id, id is needed for uniqueness)
http://www.example.com/users/123/peter
# All Categories
http://www.example.com/categories/
# A single category listing (123 is the cat id, note: job is singular)
http://www.example.com/categories/123/job
# All Tags
http://www.example.com/tags/
# A single tag listing (123 is the tag id, note: car is singular)
http://www.example.com/tags/123/car
# A single post
http://www.example.com/posts/123/my-title
Run Code Online (Sandbox Code Playgroud)
有什么建议或改进的地方吗?
谢谢.
这完全取决于你的应用程序最重要的主题是什么.假设应用程序的主要主题是帖子,那么帖子的URL必须"更接近"根URL.
所以它们看起来像这样:
# A single post
http://www.example.com/123-my-post-title
# All Users:
http://www.example.com/users/
# A single user (supposing the username must be unique)
http://www.example.com/users/peter
# All Categories
http://www.example.com/categories/
# A single category listing (supposing the category name must be unique)
http://www.example.com/categories/job
# All Tags
http://www.example.com/tags/
# A single tag listing (supposing tags must be unique)
http://www.example.com/tags/car
Run Code Online (Sandbox Code Playgroud)
这涉及您的路线中的2个变化:
1)删除网址中的"/ posts /".为此,您可以像这样声明您的资源:
resources :posts, :path => "/"
Run Code Online (Sandbox Code Playgroud)
2)除了post#show之外的所有URL中的id(不同用户的帖子有时可能会有相同的标题,如果没有,你也可以在这些情况下省略ID).
要做到这一点,应该覆盖to_param模型中的方法,如下所示:
class Post < ActiveRecord::Base
def to_param
"{id}-#{title.parameterize}"
end
end
Run Code Online (Sandbox Code Playgroud)
或者如果你发现压倒一切困难,请使用friendly_id gemto_param.