3
1

More than 3 years have passed since last update.

【Rails】Routing設定について

Last updated at Posted at 2020-11-27

本投稿の目的

・Rails学習の議事録です。


学習に使った教材

Udemyの以下2つの教材を参考にまとめました。
"はじめてのRuby on Rails入門-RubyとRailsを基礎から学びWebアプリケーションをネットに公開しよう"
"フルスタックエンジニアが教える 即戦力Railsエンジニア養成講座"


○RESTfull

・HTTPメソッドにそってWebのリソースを設計する設計思想
・RailsのRouting設定はこの思想を表現したようなもの

【HTTPメソッド】
・GET  リソースの取得
・POST リソースの作成
・PATCH/PUT リソースの更新
・DELTE リソースの削除

○Routingとは?

以下の①~④を指定する設定

①どのHTTPメソッドで
②どのurlへアクセスした際に
③どのcontrollerの
④どのアクションを実行するか

○Routing設定方法

・/config/routes.rb を開く
・このファイルを編集することでrouting変更が可能
*(rails g controller アクション名で記述したroutingが自動記述済み)

【rootの設定】

・urlに"/"でアクセスした際のrouting設定
・以下を記述 (*アクション名は"#"で記載することに注意)

qiita.rb
root 'controller名#アクション名''

【例:rootでquestions controllerのindexアクションを実行したい場合】

qiita.rb
root 'questions#index'

【書き方①】

・HTTPメソッドでPrefix_pathのurlへアクセスするとtoo以降のcontrollerでアクションを実行
・という設定を意味する
・以下を記述 (Prefixの部分は _pathを除くことに注意)

qiita.rb
HTTPメソッド 'Prefix(_pathは除く)', too: 'controller名#アクション名'

【例:boards controllerのnewアクションを想定】

qiita.rb
get 'boards/new', too: 'boards#new'

【書き方②】

【基本的な記述】
・Railsでdefaultで設定された分のroutingが自動で設定可能
・以下を記述

qiita.rb
resources :controller

【応用的な記述】
・指定したアクション名のみをroutingで設定可能
・以下を記述

qiita.rb
resources :controller, only: [:アクション名1, :アクション名2]

【例:questions controller を想定】
・questions controller のindex,create,new,showに関連するroutingのみ自動設定

qiita.rb
resources :questions, only:[:index :create :new :show]

○Routing確認方法

【確認方法①(ターミナル)】
・ターミナルに以下を記述

rails routes

*【出力結果】
・今回は 【例:questions controller を想定】 の条件下での場合の出力結果

      Prefix  Verb   URI Pattern                      Controller#Action                                                                                      
    questions GET    /questions(.:format)             questions#index
              POST   /questions(.:format)             questions#create
 new_question GET    /questions/new(.:format)         questions#new
     question GET    /questions/:id(.:format)         questions#show

【解説】
・Prefix_pathで定義されたurlへアクセスした際に,それぞれのcontrollerのアクションを実行する
・これらは,routes.rbで設定したため作成された設定である

【確認方法②(Webブラウザ)】
・/rails/info/routes のpathにアクセス
・設定済みのルート情報を確認

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