简体   繁体   中英

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

One of the entries in my config/routes.rb :

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

As you can observe, the URL path and the method name that it corresponds to in the controller is the same. Does Rails provide a shorthand in such cases?

Yep! Rails magic will let you just write: get "enumerators/job_type" in your routes file, as long as your controller name is EnumeratorsController and the method is job_type

Remember you can always check the routes it's creating by running bundle exec rake routes

You can use namespace like the below:

namespace :enumerators do 
  get "job_type" 
end

More info for namespace:

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

Blending the two answers, here are the best way to the worst way to do the routing:

  1. Best

     namespace :enumerators do get "job_type" get "something_else" end 
  2. Worse

     get "enumerators/job_type" get "enumerators/something_else" 
  3. Worst

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM