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

【Rails初心者】ルーティングって何?実際のコードで学んだこと

Posted at

【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のルーティングは奥が深く、まだまだ理解しきれていない部分もありますが、少しずつ学んでいます。
間違いがありましたら、申し訳ございません。


参考リンク

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