ruby-on-rails - 博客平台推荐的Url格式

标签 ruby-on-rails ruby api url rest

我正在构建一个博客平台(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/

相关文章:

ruby-on-rails - 与 Rails 3 站点的完整谷歌日历集成

ruby - 使用 mechanize-ruby 提交登录表单时,我可以使用变量来表示字段名称吗?

Laravel 8 在斜杠上行为不端

ruby-on-rails - 运行 Ruby 代码的 Google OpenID 示例?

ruby-on-rails - 在所有 Rails 助手中将协议(protocol)更改为 https

ruby - 如何从 Ruby 中的字符串中去除制表符?

api - 如何从服务器和客户端角度使用3Scale的 `authrep`函数?

java - 如何使用Azure认知系统?

javascript - `setInterval` 是否会阻止用户输入?

sql - Rails 控制台和 Rails 服务器日志中输出的颜色是什么意思?