如何重命名 URL 中的 REST 路由? [英] How to rename REST routes in URL?

查看:23
本文介绍了如何重命名 URL 中的 REST 路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 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.

有什么方法可以在不触及应用程序中的任何其他代码的情况下做到这一点?(即在应用程序内部,它仍然是 appleApplesController)

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"}

但这只是改变了路线的名称",而不是 URL(所以 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

资源 :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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆