了解Rails扩展了路由搜索以包括动态URL参数

101 阅读2分钟

随着 Rails 应用程序的增长,路由文件可能会变得相当大。 Rails 提供了两种搜索路由的方法:http://localhost:3000/rails/info/routesrails routes 。网页界面使搜索路由变得容易,但大多数开发者更喜欢命令行界面。

使用rails routes 可以显示应用程序中的所有路由,而rails routes -g cats 可以找到所有与字符串cats 匹配的路由。然而,要在命令行中找到要找的路由可能很困难,尤其是在路由包含动态 URL 参数的情况下。

例如,要搜索与cats/10/toys/15 匹配的路由,就必须搜索cats/:cat_id/toys/:id 。这可能很令人沮丧,特别是当我们不确定动态URL参数的名称时。

之前

让我们考虑一个路由文件,它看起来像这样。

  resources :cats do
    resources :toys
  end

现在,如果我们搜索rails routes -g cats/:cat_id/toys/:id ,我们会得到以下输出。

  Prefix Verb   URI Pattern                      Controller#Action
  cat_toy GET    /cats/:cat_id/toys/:id(.:format) toys#show
          PATCH  /cats/:cat_id/toys/:id(.:format) toys#update
          PUT    /cats/:cat_id/toys/:id(.:format) toys#update
          DELETE /cats/:cat_id/toys/:id(.:format) toys#destroy

然而,搜索rails routes -g cats/10/toys/15 ,则没有任何结果。

之后

感谢这个PR,Rails现在支持在rails routes 命令中搜索动态的URL参数,这使得我们更容易找到要找的路由。

现在,如果我们搜索rails routes -g cats/10/toys/15 ,我们会得到以下输出。

  Prefix Verb   URI Pattern                      Controller#Action
  cat_toy GET    /cats/:cat_id/toys/:id(.:format) toys#show
          PATCH  /cats/:cat_id/toys/:id(.:format) toys#update
          PUT    /cats/:cat_id/toys/:id(.:format) toys#update
          DELETE /cats/:cat_id/toys/:id(.:format) toys#destroy

注意,输出中没有显示indexcreate 的选项。 这是因为rails routes 命令只显示与字符串cats/10/toys/15 完全匹配的路由,不允许模糊匹配。

要搜索indexcreate 路线,我们可以搜索rails routes -g cats/10/toys

  Prefix Verb URI Pattern                  Controller#Action
  cat_toys GET  /cats/:cat_id/toys(.:format) toys#index
         POST /cats/:cat_id/toys(.:format) toys#create

有趣的是,搜索rails routes -g cats/10/toys/new 只做了一个模糊匹配,并没有只显示new 途径。 也许这是未来可以改进的地方。

  Prefix Verb   URI Pattern                      Controller#Action
  new_cat_toy GET    /cats/:cat_id/toys/new(.:format) toys#new
  cat_toy GET    /cats/:cat_id/toys/:id(.:format) toys#show
          PATCH  /cats/:cat_id/toys/:id(.:format) toys#update
          PUT    /cats/:cat_id/toys/:id(.:format) toys#update
          DELETE /cats/:cat_id/toys/:id(.:format) toys#destroy