Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

ruby on rails - Difference between resource and resources methods

What is the logical difference between resource and resources methods

Here is some examples:

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

It looks like method resource does not create route for index, and helpers in some cases are different (new_order and new_orders). Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At a high level, the intent of resource is to declare that only one of these resources will ever exist. For example:

resource :profile, :only => [:edit, :update]

As a user, I should only be able to update my own profile. I should never be able to edit other users' profiles, so there's no need for a URL scheme like /users/1/profile/edit. Instead, I use /profile/edit, and the controller knows to use the current user's ID rather than the ID passed in the URL (since there is none).

That's why you don't get an index action with resource: there's only one resource, so there's no sense in "listing" them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...