resource
和resources
方法之间的逻辑差异
以下是一些例子:
resource :orders, :only => [:index, :create, :show]
> rake routes
orders POST /orders(.:format) orders#create
GET /orders(.:format) orders#show
resources :orders, :only => [:index, :create, :show]
> rake routes
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
order GET /orders/:id(.:format) orders#show
resource :orders
> rake routes
orders POST /orders(.:format) orders#create
new_orders GET /orders/new(.:format) orders#new
edit_orders GET /orders/edit(.:format) orders#edit
GET /orders(.:format) orders#show
PUT /orders(.:format) orders#update
DELETE /orders(.:format) orders#destroy
resources :orders
> rake routes
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
new_order GET /orders/new(.:format) orders#new
edit_order GET /orders/:id/edit(.:format) orders#edit
order GET /orders/:id(.:format) orders#show
PUT /orders/:id(.:format) orders#update
DELETE /orders/:id(.:format) orders#destroy
看起来方法resource
不会为index
创建路由,并且在某些情况下帮助程序是不同的(new_order和new_orders)。为什么呢?
答案 0 :(得分:97)
在较高的层面上,resource
的意图是声明这些资源中只有一个会存在。例如:
resource :profile, :only => [:edit, :update]
作为用户,我应该只能更新自己的个人资料。我永远不能编辑其他用户的个人资料,因此不需要像/users/1/profile/edit
这样的网址方案。相反,我使用/profile/edit
,并且控制器知道使用当前用户的ID而不是URL中传递的ID(因为没有)。
这就是为什么你没有index
resource
行动的原因:只有一个资源,所以“列出”它们是没有意义的。
答案 1 :(得分:43)
实际上你是对的,resource
不应该创建索引操作,除非你明确地要求索引操作,这样:
resource :orders, :only => [:index, :create, :show]
助手也应该有所不同,但与你的例子不同,因为惯例是使用带有resource
方法的单数形式,带有resources
resources :orders
=> rake routes
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
new_order GET /orders/new(.:format) orders#new
edit_order GET /orders/:id/edit(.:format) orders#edit
order GET /orders/:id(.:format) orders#show
PUT /orders/:id(.:format) orders#update
DELETE /orders/:id(.:format) orders#destroy
resource :order
=> rake routes
order POST /order(.:format) orders#create
new_order GET /order/new(.:format) orders#new
edit_order GET /order/:id/edit(.:format) orders#edit
GET /order/:id(.:format) orders#show
PUT /order/:id(.:format) orders#update
DELETE /order/:id(.:format) orders#destroy
逻辑上的区别在于声明您在应用中逻辑上不能拥有复数资源,例如Admin或其他