RailsルーターはリクエストURLを解析して適切なコントローラーのアクションへディスパッチすると同時に、ヘルパーを介して逆引きのURLやパスを生成します。
リソースフルルーティング (resources)
Rails.application.routes.draw do
root "home#index"
resources :articles do
# メンバーアクション(特定リソースを操作: /articles/:id/publish)
member do
patch :publish
end
# コレクションアクション(リソース全体を操作: /articles/search)
collection do
get :search
end
# ネストされたリソース (/articles/:article_id/comments)
resources :comments, only: [:create, :destroy]
end
end
ルートパスヘルパー (Route Path Helpers)
| アクション | パスヘルパー | 生成されるURL |
|---|---|---|
index |
articles_path |
/articles |
show |
article_path(@article) |
/articles/:id |
new |
new_article_path |
/articles/new |
edit |
edit_article_path(@article) |
/articles/:id/edit |
名前空間とスコープ (Namespaces & Scopes)
# Namespace: URLに /admin を付与しコントローラを Admin:: に配置
namespace :admin do
resources :users
end
# /admin/users に対するリクエストを Admin::UsersController にルーティング
# Scope: コントローラ名前空間を変更せずにURLプレフィックスのみ付与
scope "/v1" do
resources :posts
end
カスタム単一ルートとリダイレクト
# カスタムHTTPメソッドマッピング
get '/about', to: 'pages#about'
post '/webhook', to: 'webhooks#receive'
# 301 恒久的リダイレクト
get '/stories', to: redirect('/articles')