LoginSignup
7
16

More than 5 years have passed since last update.

Ruby on Rails resourcesメソッドのネスト例

Last updated at Posted at 2017-05-18

Ruby on Rails ルーティングに関して、resourcesメソッドの整理。
resouresメソッドとは、7つのアクションへのルーティングをまとめて表記できるもの。
ルーティングを一つ一つ手打ちすることも可能だけど、resourcesメソッドはよく使う機能のルーティングがひとまとめになっていて便利。
参考文献:Rails公式ドキュメント 

resourcesメソッド使用例(ネストなし)

ネストなし、tweetsコントローラのみ。

routes.rb
Rails.application.routes.draw do
  resources :tweets
end

# の'resources :tweets'はすなわち

GET    '/tweets'          => 'tweets#index'   # 一覧画面を生成
GET    '/tweets/:id'      => 'tweets#show'    # 詳細画面を生成
GET    '/tweets/new'      => 'tweets#new'     # 登録画面を生成
POST   '/tweets/create'   => 'tweets#create'  # 登録処理
GET    '/tweets/:id/edit' => 'tweets#edit'    # 編集画面を生成
PUT    '/tweets/:id'      => 'tweets#update'  # 更新処理
DELETE '/tweets/:id'      => 'tweets#destroy' # 削除処理

createはPOST、その他PUT・GETなどは自分で編集せずとも自動的にそのように設定されている。
便利なフレームワーク。

resourcesメソッド使用例(ネストあり)

ネストあり、tweetsコントローラに加えて、commentsコントローラとusersコントローラ。

routes.rb
Rails.application.routes.draw do
  # 実際はここに devise_for :users (ログイン・ログアウト機能など)
  resources :tweets do
    resources :comments, only: [:create]
  end
  resources :users, only: [:show]

end

# の'resources :tweets 〜 only: [:show]'はすなわち

GET    '/tweets'          => 'tweets#index'   # 一覧画面を生成
GET    '/tweets/:id'      => 'tweets#show'    # 詳細画面を生成
GET    '/tweets/new'      => 'tweets#new'     # 登録画面を生成
POST   '/tweets/create'   => 'tweets#create'  # 登録処理
GET    '/tweets/:id/edit' => 'tweets#edit'    # 編集画面を生成
PUT    '/tweets/:id'      => 'tweets#update'  # 更新処理
DELETE '/tweets/:id'      => 'tweets#destroy' # 削除処理

POST   '/tweets/:id/comments' => 'comments#create' # ツイートにコメント

GET    '/users/:id'       => 'users#show'     # ユーザーのマイページを表示 

7
16
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
16