如何命名资源上的路线? [英] How to name a route on a resource?

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

问题描述

如果我有一个控制器Home,且具有单个操作index,我知道我可以编写:

If I have a controller Home with a single action index, I know I can write:

get 'home' => 'home#index"

,我将自动获得命名的路由home_path.

and I will automatically have the named route home_path.

但是,如果我这样定义它:

But if I define it like so:

resources :home, only: :index

我得到了路线home_index_path.为什么会这样,如果使用resources约定,如何创建命名路由home_path.

I get the route home_index_path. Why is that and how can I create the named route home_path, if I use the resources convention.

推荐答案

Rails定义了routes文件中所有资源的标准命名约定.请参阅资源路由指南".

Rails defines a standard naming convention for all resources in the routes file. See the Rails Guide on Resource Routing.

您还可以运行bundle exec rake routes来查看您在应用程序中定义的路由的名称.

You can also run bundle exec rake routes to see the names for the routes you've defined in your application.

在您的示例resources :home, only: :index中,"homes#index"操作的命名路由为homes_pathhomes_url.

In the case of your example, resources :home, only: :index, the named route for the "homes#index" action would be homes_path or homes_url.

更新:

您可能更喜欢resource :home, only: :show,其命名路由为home_pathhome_url.同样,访问家庭资源(单数)的路径将是/home,而家庭资源(多个)索引将是/homes.

You may prefer resource :home, only: :show which would have a named route of home_path or home_url. Also the path to access the home resource (singular) would be /home whereas the the home resources (plural) index would be /homes.

这篇关于如何命名资源上的路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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