【Rails初心者】ルーティングって何?実際のコードで学んだことまとめておく
こんにちは。
Rails初学者の私が、ルーティングを学びながらつまずいた事をまとめてみました。
ルーティングって何?
Railsのルーティングは、URLとコントローラーのアクションを結びつける役割を担う。
例えば /articles
にアクセスしたときに、どのコントローラー・アクションを呼び出すのか?というのを決めている。
基本の形
Rails.application.routes.draw do
resources :articles
end
上記のように書くと、articles_controller に対して以下のようなルートが自動で作成される。
HTTPメソッド | パス | アクション |
---|---|---|
GET | /articles | index |
GET | /articles/:id | show |
POST | /articles | create |
PATCH | /articles/:id | update |
DELETE | /articles/:id | destroy |
GET | /articles/new | new |
GET | /articles/:id/edit | edit |
ネストしたルーティング
親リソースの中にネストすることで、例えば「あるアカウントのフォロー・アンフォロー機能」を実装できる。
resources :accounts, only: [:show] do
resources :follows, only: [:create]
resources :unfollows, only: [:create]
end
こんなURLになる
/accounts/:account_id/follows
/accounts/:account_id/unfollows
scope module で名前空間を分ける
scope module: :apps do
resources :favorites, only: [:index]
resource :profile, only: [:show, :edit, :update]
resource :timeline, only: [:show]
end
URLはそのまま/favorites
などになるが、呼び出されるのはApps::FavoritesController
のようにApps
名前空間配下のコントローラーとなるらしい。
※名前空間という意味もあまりわかっていないですが
実際のコントローラー例
class Apps::FavoritesController < Apps::ApplicationController
def index
@articles = current_user.favorite_articles
end
end
共通の認証処理もApps::ApplicationController
にまとめて書くことが可能
class Apps::ApplicationController < ApplicationController
before_action :authenticate_user!
end
APIのルーティング
/api/articles/1/comments
にアクセスしたとき、JSON形式でコメント一覧を返したり、新しいコメントを作成したりできる。
namespace :api, defaults: {format: :json} do
scope '/articles/:article_id' do
resources :comments, only: [:index, :create]
resource :like, only: [:show, :create, :destroy]
end
end
JavaScriptと連携する
APIを使った処理をJavaScript
から呼び出す例
axios.get(`/api/articles/${articleId}/comments`)
.then((response) => {
const comments = response.data
comments.forEach((comment) => {
appendNewComment(comment)
})
})
Railsのルーティングと連携して、非同期通信(Ajax)でコメントを取得・表示している
Railsのルーティングは奥が深く、まだまだ理解しきれていない部分もありますが、少しずつ学んでいます。
間違いがありましたら、申し訳ございません。