resources 方法裡面其實還可以在包 resources,在後面會提到 model 之間關連性,例如一個 User 可能會有很多 Articles,Route 可能會這樣寫:
1 2 3 4 5
Rails.application.routes.draw do resources :usersdo resource :articles end end
終端機輸入 $ rails routes -c articles 查詢路徑可以看到如下
1 2 3 4 5 6 7 8
Prefix Verb URI Pattern Controller#Action new_user_articles GET /users/:user_id/articles/new(.:format) articles#new edit_user_articles GET /users/:user_id/articles/edit(.:format) articles#edit user_articles GET /users/:user_id/articles(.:format) articles#show PATCH /users/:user_id/articles(.:format) articles#update PUT /users/:user_id/articles(.:format) articles#update DELETE /users/:user_id/articles(.:format) articles#destroy POST /users/:user_id/articles(.:format) articles#create
resources :articlesdo resources :comments, only: [:index, :new, :create] # 這3種 action 需要標出 article id end resources :comments, only: [:show, :edit, :update, :destroy] # 這些不需要標出 article id
1 2 3 4 5 6 7 8 9 10
Prefix Verb URI Pattern Controller#Action article_comments GET /articles/:article_id/comments(.:format) comments#index POST /articles/:article_id/comments(.:format) comments#create new_article_comment GET /articles/:article_id/comments/new(.:format) comments#new edit_comment GET /comments/:id/edit(.:format) comments#edit comment GET /comments/:id(.:format) comments#show PATCH /comments/:id(.:format) comments#update PUT /comments/:id(.:format) comments#update DELETE /comments/:id(.:format) comments#destroy
上面的寫法可以利用 shallow 來簡化如下,產生出來的路徑都是相同。
1 2 3
resources :articlesdo resources :comments, shallow:true end
collection 與 member
如果預設的路徑不夠使用,且層層包裹之中,又希望設計要或不要帶有前面一層的 id 可以這樣表示 collection => 沒有 id member => 有 id
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Rails.application.routes.draw do resources :friendsdo collection do # /friends/confirmed get :confirmed end member do # /friends/:id/status post :status # /friends/:id/ delete :destroy end end end
對應路徑如下:
1 2 3 4 5 6 7 8 9 10 11 12
Prefix Verb URI Pattern Controller#Action confirmed_friends GET /friends/confirmed(.:format) friends#confirmed status_friend POST /friends/:id/status(.:format) friends#status friend DELETE /friends/:id(.:format) friends#destroy friends GET /friends(.:format) friends#index POST /friends(.:format) friends#create new_friend GET /friends/new(.:format) friends#new edit_friend GET /friends/:id/edit(.:format) friends#edit GET /friends/:id(.:format) friends#show PATCH /friends/:id(.:format) friends#update PUT /friends/:id(.:format) friends#update DELETE /friends/:id(.:format) friends#destroy