如何在URL中重命名REST路由? [英] How to rename REST routes in URL?
问题描述
鉴于我有一个名为 Apple
的模型,它有一个控制器 ApplesController
,路由为:
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"}
除了URL中的 apple将由 car代替之外,我希望所有代码保持相同。因此,URL / apples / new
将变为 / cars / new
。
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
.
有什么方法可以在不触摸应用程序中任何其他代码的情况下执行此操作? (即在应用程序内部,它仍然是 apple
和 ApplesController
)
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
)
我尝试了:as
选项:
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"}
但这只是更改了路线的名称 ,而不是网址(因此 new_apple_path
变成了 new_car_path
,而成为 new_car_path
仍指向 / apples / new
而不是 / cars / new
)
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
)
推荐答案
您想要做的就是传递:path
选项
What you will want to do is pass in the :path
option
resources:apples,:path => 汽车
这会将您所有的路线引用替换为 / apples
到 / cars
This replace all your route references with /apples
to /cars
请参阅: http://guides.rubyonrails.org/routing.html ,第4.7节翻译路径
See: http://guides.rubyonrails.org/routing.html, Section 4.7 Translating Paths
这篇关于如何在URL中重命名REST路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!