記事概要
Ruby on Railsのルーティングについて、まとめる
前提
- Ruby on Railsでアプリケーションを作成している
基本情報
ファイルパス
config/routes.rb
記載方法
- 不要なコメントを削除
config/routes.rb
Rails.application.routes.draw do end
- 処理を記述する
config/routes.rb
Rails.application.routes.draw do # 処理を記述 end
Prefix
ルーティングのURI Pattern
に名前をつけて変数化したもの
ルートパス
root_path
と表記できる
Prefixが非表示
Prefixが非表示の場合、上段のPrefixを指定する
# createアクションのPrefixは「tweets」
Prefix Verb URI Pattern Controller#Action
tweets GET /tweets(.:format) tweets#index
POST /tweets(.:format) tweets#create
new_tweet GET /tweets/new(.:format) tweets#new
まとめ
resourcesメソッド
7つのアクションへのルーティングを自動生成するメソッド
Rails.application.routes.draw do
# 「/コントローラー名」のパスに対応するルーティングが生成される
resources :コントローラー名
end
resources :tweets
によって設定されるルーティング
GET /tweets(.:format) tweets#index
POST /tweets(.:format) tweets#create
GET /tweets/new(.:format) tweets#new
GET /tweets/:id/edit(.:format) tweets#edit
GET /tweets/:id(.:format) tweets#show
PATCH /tweets/:id(.:format) tweets#update
PUT /tweets/:id(.:format) tweets#update
DELETE /tweets/:id(.:format) tweets#destroy
onlyオプション
指定したアクションのルーティングのみを自動生成する
Rails.application.routes.draw do
# onlyオプションで指定したアクション名に対応するルーティングが生成される
resources :コントローラー名, only: :アクション名
end
resources :tweets, only: :index
によって設定されるルーティング
GET /tweets(.:format) tweets#index
複数アクションを指定する場合
Rails.application.routes.draw do
# onlyオプションで指定したアクション名に対応するルーティングが生成される
resources :コントローラー名, only: [:アクション名, :アクション名]
end
URIパターンを記述
config/routes.rb
Rails.application.routes.draw do
HTTPメソッド 'URIパターン', to: 'コントローラー名#アクション名'
end
ルートパスの設定
/
へリクエストが送られた際のルーティングを設定する
# "/"へリクエストが送られた際、実行するコントローラーのアクションを記述
root to: '[コントローラー名]#[アクション名]'
# "/"へリクエストが送られた際、tweetsコントローラーのindexアクションを実行する
root to: 'tweets#index'
ルーティングのネスト
あるコントローラーのルーティングの中に、別のコントローラーのルーティングを記述すること
Rails.application.routes.draw do
resources :親となるコントローラー do
resources :子となるコントローラー
end
end
- tweetsコントローラーのルーティングの中にcommentsコントローラーのルーティングを記述
- コメントはツイートに紐づく形で作成される
resources :tweets do resources :comments, only: :create end
- URIパターンの
:tweet_id
に、コメントと結びつくツイートのidを記述する - paramsのなかに
tweet_id
というキーでパラメーターが追加され、コントローラーで扱えるPrefix Verb URI Pattern Controller#Action tweet_comments POST /tweets/:tweet_id/comments(.:format) comments#create
collection
生成されるルーティングのURLと実行されるコントローラーを任意にカスタムできる
:id
がつかないため、複数のデータを表示できる
resources :tweets do
collection do
get 'search'
end
end
Prefix Verb URI Pattern
search_tweets GET /tweets/search(.:format) tweets#search
member
生成されるルーティングのURLと実行されるコントローラーを任意にカスタムできる
:id
がつくため、特定のデータのみを表示する
resources :tweets do
member do
get 'search'
end
end
Prefix Verb URI Pattern
search_tweet GET /tweets/:id/search(.:format) tweets#search
Ruby on Railsまとめ
ルーティング