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)。为什么?
最佳答案
从较高的层面来说,resource
的目的是声明这些资源中只有一个会存在。例如:
resource :profile, :only => [:edit, :update]
作为用户,我应该只能更新我自己的个人资料。我应该永远无法编辑其他用户的个人资料,因此不需要像 /users/1/profile/edit
这样的 URL 方案。相反,我使用 /profile/edit
,并且 Controller 知道使用当前用户的 ID,而不是 URL 中传递的 ID(因为没有)。
这就是为什么您没有使用 resource
获得 index
操作的原因:只有一种资源,因此“列出”它们是没有意义的。
关于ruby-on-rails - 资源和资源方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9194767/