openSUSE:Build Service Future Routing

跳转到:导航搜索

按名称 vs 按 ID 路由

给定以下示例模型(简化的 MySQL)

   CREATE TABLE `architectures` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `name` varchar(255) NOT NULL,
     PRIMARY KEY (`id`),
   );

假设存在一个对应的 Ruby 模型和控制器,其中包含 'index'、'show' 和 'update' 操作。


OBS-2.x 的当前状态

可能的请求

   GET /architecture                   <- listing of all
   GET /architecture/x86_64            <- show arch with name "x86_64" (secondary key)
   PUT /architecture/x86_64            <- update arch with name "x86_64 (secondary key)

生成的 routes.rb 条目

   map.connect 'architecture',       :controller => 'architecture', :action => 'index'
   map.connect 'architecture/:name', :controller => 'architecture', :action => 'show',   :conditions => {:method => :get}
   map.connect 'architecture/:name', :controller => 'architecture', :action => 'update', :conditions => {:method => :put}

优点

  • 更易于人类阅读的 URL
  • 当已知 'name' 时,无需进行其他 'name' 查找。

缺点

  • 为了快速查找,需要在 'architecture' 表的 'name' 列上创建一个索引
  • 仍然无法保证给定的 'name' 实际存在
  • 通过主键进行连接_始终_涉及查找 'name'(尽管是在索引中)
  • 如果您希望路由是持久的(即在 pastebin、短链接或缓存中找到),则永远不能更改 arch 的 'name'。
    • 对于架构来说,这问题不大,但通常来说不好

期望状态(在遥远的银河系中)

可能的请求

   GET /architectures                  <- listing of all
   GET /architectures/1                <- show arch with id 1 (primary key)
   PUT /architectures/1                <- update arch with id 1 (primary key)

生成的 routes.rb 条目

   map.resources :architectures

优点

  • 始终按主键(id)查找,更快!!!
  • 可能不需要 'name' 上的索引,这意味着索引的内存需求减半
  • Rails 会自动生成路由,并正确地将 HTTP 方法(GET、PUT)映射到正确的控制器操作。
  • 通过主键进行连接_可能_涉及查找 'name'(希望是在索引中)
  • 第一步列出可以减少用户查询不存在的 arch 'name' 的可能性
  • 这是每个人都在做的事情(可能不是一个强有力的论点)

缺点

  • URL 可读性较差
  • 要获取名称为 'x86_64' 的 arch,需要进行查找。但这对于 UI 来说影响不大,用户总是从列表中选择。