ruby-on-rails - 资源和资源方法之间的区别

标签 ruby-on-rails ruby-on-rails-3 routes

resourceresources 方法之间的逻辑差异是什么

以下是一些示例:

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/

相关文章:

ruby-on-rails - 开始使用 rails 6 : how to start a blank new rails 6 application

ruby-on-rails - Paperclip::Attachment 在使用 FactoryGirl 时作为字符串传递

javascript - 页面.js : Instead of Hashbang just Hash?

asp.net-mvc - MVC 路由中允许空参数

jquery - Symfony2 和 Jquery UI 选项卡

html - text_area 文本格式

mysql - 尝试部署 Rails 应用程序时获取 ActiveRecord::AdapterNotSpecified: 'old_production' 数据库未配置

ruby-on-rails - Rails - 从参数哈希中获取所有键

ruby-on-rails - 如何将来自 Twitter 的 Bootstrap 样式表与我在 Rails 中的现有样式表一起使用,而不会弄乱一切?

ruby-on-rails - Rails 状态 406 POST 响应