我正在将一个Rails 2.3.8版本迁移到Rails 3.0,所以我重写了我的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] }
endRails 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的想法都将不胜感激。
发布于 2011-06-25 19:50:37
因为您的资源名为: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)在第一种情况下,搜索“照片”,在第二种情况下,搜索“照片索引”。
发布于 2011-06-25 19:46:51
您应该根据需要使用resource :planner或resources :planners。要了解单一资源及其差异,请查看Rails Guides。
发布于 2015-11-13 08:58:07
在Semyon Perepelitsa的响应之后,请注意resource :planner期望控制器的名称是PlannersController,而resources :planners期望的是PlannerController。
如果在从资源更改为资源时不想重命名控制器,可以通过指定resource :planner, controller: :planner来覆盖默认值。
https://stackoverflow.com/questions/6476763
复制相似问题