Rails路由shorthand当URL路径与方法名相同?

Rails routing shorthand when URL path is the same as method name?

我的条目之一 config/routes.rb:

get "enumerators/job_type", to: "enumerators#job_type"

可以看到,URL路径和它在控制器中对应的方法名是一样的。 Rails 在这种情况下是否提供 shorthand?

是的! Rails magic 会让你在你的路由文件中写:get "enumerators/job_type",只要你的控制器名称是 EnumeratorsController 并且方法是 job_type

请记住,您始终可以通过 运行 bundle exec rake routes

检查它创建的路由

您可以使用如下命名空间:

namespace :enumerators do 
  get "job_type" 
end

命名空间的更多信息:

http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

混合两个答案,这里是进行路由的最佳方式和最差方式:

  1. 最佳

    namespace :enumerators do 
      get "job_type"
      get "something_else"
    end
    
  2. 更糟

    get "enumerators/job_type"
    get "enumerators/something_else"
    
  3. 最差

    get "enumerators/job_type", to: "enumerators#job_type"
    get "enumerators/something_else", to: "enumerators#something_else"