Rails 3 route将_index附加到路由名称
我正在将Rails 2.3.8版本迁移到Rails 3.0,因此我重写了我的路由文件。 当我使用rake routes
列出rake routes
,我看到一些路由名称附加了_index
。 我无法弄清楚为什么会这样。
相关路线:
Rails 2.3.8:
map.namespace "tracker", :path_prefix => "" do |planner| planner.resources :planner, :collection => {:step1 => :get, :add => :get, :unsubscribe => [:get, :post] } end
Rails 3.0路线:
namespace "tracker", :path => "" do resources :planner do collection do get :step1 get :add get :unsubscribe post :unsubscribe end end end
rake routes
输出
Rails 2.3.8
step1_tracker_planner GET /planner/step1(.:format) add_tracker_planner GET /planner/add(.:format) unsubscribe_tracker_planner GET /planner/unsubscribe(.:format) POST /planner/unsubscribe(.:format)
Rails 3.0
step1_tracker_planner_index GET /planner/step1(.:format) add_tracker_planner_index GET /planner/add(.:format) unsubscribe_tracker_planner_index GET /planner/unsubscribe(.:format) POST /planner/unsubscribe(.:format)
关于为什么添加这个_index
任何想法都将非常感激。
这是因为你的资源被命名为:planner
而不是:planners
,Rails决定将_index添加到嵌套在下面的任何集合。 我猜这是为了可读性。
集合中命名的动作通常转换为动词,所以我可以看出为什么这是有意义的。 以路线文档中给出的典型照片资源示例为例:
resources :photos do collection do get 'search' end end search_photos GET /photos/search(.:format)
但如果相反我们称资源’照片’……
resources :photo do collection do get 'search' end end search_photo_index GET /photo/search(.:format)
在第一种情况下,您搜索“照片”,在第二种情况下,您搜索“照片索引”。
您应该使用任何一种resource :planner
resources :planners
具体取决于您的需求。 要了解奇异资源及其差异,请查看Rails指南 。
继Semyon Perepelitsa的回复之后,请注意resource :planner
期望控制器的名称是PlannersController
,而resources :planners
期望PlannerController
。
如果您不想在从资源更改为资源时重命名控制器,则可以通过指定resource :planner, controller: :planner
来覆盖默认值。