1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ルーティングとHTTPメソッドの設定

Last updated at Posted at 2023-03-31

HTTPメソッド

HTTPメソッドには、GET、POST、PATCH、DELETEがあります。
HTTPのリクエスト対象をリソースと呼ぶが、HTTPメソッドはそのリソースに対する操作の種類を表す名前です。

ルーティングとHTTPメソッドの対応表

HTTP 操作 path コントローラ#アクション名 目的
GET 取得 /photos photos#index すべての写真の一覧を表示
GET 取得 /photos/new photos#new 写真を1つ作成するためのHTMLフォームを返す
POST 追加 /photos photos#create 写真を1つ作成する
GET 取得 /photos/:id photos#show 特定の写真を表示する
GET 取得 /photos/:id/edit photos#edit 写真編集用のHTMLフォームを1つ返す
PATCH 更新 /photos/:id photos#update 特定の写真を更新する
DELETE 削除 /photos/:id photos#destroy 特定の写真を削除する

※理由のない限り、基本のアクション名から選ぶ方が良い。
 記述量が減り、ソースコードの意図が明確になるため

ログイン・ログアウト機能のルーティング実装例

ルーティング設計

アクション内容 HTTP URLパス コントローラ名 アクション名
ログインフォームを表示する GET /staff/login staff/sessions new
ログインする POST /staff/session staff/sessions create
ログアウトする DELETE /staff/session staff/sessions new

実装例

config/routes.rb
Rails.application.routes.draw do
  namespace :staff do
    root "top#index"
    get "login" => "sessions#new", as: :login
    post "session" => "sessions#create", as: :session
    delete "session" => "sessions#destroy"
  end

4行目〜5行目の末尾にあるasオプションは、ルーティングに名前を付けるためのものです。
こうしておくと、ERBテンプレートの中で :staff_login や :staffsession といったように
シンボルを用いてURLパスを参照できるようになります。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?