我正在构建一个博客平台(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
有什么建议或需要改进的地方吗?
谢谢。
最佳答案
这完全取决于您的应用最重要的主题是什么。假设应用的主要主题是帖子,那么帖子的 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
这涉及到您的路线的 2 处更改:
1) 去掉 URL 中的“/posts/”。为此,您可以像这样声明您的资源:
resources :posts, :path => "/"
2) 除 post#show 之外的所有 URL 中的 ID(来自不同用户的帖子有时可能具有相同的标题,如果不是,在这些情况下您也可以省略 ID)。
要做到这一点,应该像这样重写模型中的 to_param
方法:
class Post < ActiveRecord::Base
def to_param
"{id}-#{title.parameterize}"
end
end
或使用 friendly_id gem如果您发现重写 to_param
很困难。
关于ruby-on-rails - 博客平台推荐的Url格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783173/