How to name a route on a resource?

谁都会走 提交于 2019-12-11 09:37:20

问题


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

get 'home' => 'home#index"

and I will automatically have the named route home_path.

But if I define it like so:

resources :home, only: :index

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.


回答1:


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

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

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.

UPDATE:

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.




回答2:


It is possible to use singular name controller with rails routing. try use :

resource :home, :controller => 'home'


来源:https://stackoverflow.com/questions/25724169/how-to-name-a-route-on-a-resource

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