How to rename REST routes in URL?

耗尽温柔 提交于 2019-12-03 18:45:56

问题


Give that I have a model called Apple and it has a controller ApplesController, the routes are:

resources :apples

    apples  GET    /apples (.:format)          {:controller=>"apples ", :action=>"index"}
  new_apple GET    /apples /new(.:format)      {:controller=>"apples ", :action=>"new"}
 edit_apple GET    /apples /:id/edit(.:format) {:controller=>"apples ", :action=>"edit"}

I would like to keep all code the same, except that in URLs, the "apple" would be replaced by "car". So, the URL /apples/new would become /cars/new.

Is there some way to do this while not touching any other code in the app? (i.e. internally in the app, it's still apple and ApplesController)

I tried :as option:

resources :apples, :as => "cars"

    cars    GET    /apples (.:format)          {:controller=>"apples ", :action=>"index"}
  new_car   GET    /apples /new(.:format)      {:controller=>"apples ", :action=>"new"}
 edit_car   GET    /apples /:id/edit(.:format) {:controller=>"apples ", :action=>"edit"}

But that only changed the "name" of the route, not the URL (so new_apple_path became new_car_path, but new_car_path still points to /apples/new instead of /cars/new)


回答1:


What you will want to do is pass in the :path option

resources :apples, :path => "cars"

This replace all your route references with /apples to /cars

See: http://guides.rubyonrails.org/routing.html, Section 4.7 Translating Paths




回答2:


For those seeking only to rename the helper method part:

resources :apples, as: "cars"

I.e. this would replace apples_path with cars_path, but still using the same controller/action.



来源:https://stackoverflow.com/questions/5012255/how-to-rename-rest-routes-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!