This page looks best with JavaScript enabled
⚠️

【Rails】APIのルーティングのresourcesとmodule(具体例)

 ·   ·  ☕ 1 分で読めます
✏️

Hashlogのエンドポイントを作るときにルーティング迷子になったので、単純に自分がやったものをまとめておく。

アソシエーション

User -< Tags -< Tweets

のような形でネストしています。

ルーティング

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Rails.application.routes.draw do
  resources :users, param: :uuid, only: [] do
    collection do
      resource :current, only: [], module: :users do
        scope module: :current do
          resources :tags, only: %i[index]
        end
      end
    end
    resources :tags, only: %i[index], module: :users
  end
  # resources :tagsより上に書く
  namespace :tags do
    resources :persistences, only: %i[index]
    resources :day_counts, only: %i[index]
  end
  resources :tags, only: %i[index show create update destroy] do
    resources :tweets, only: %i[index create]
  end
end

エンドポイントとコントローラ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 現在ユーザーの全タグ
GET    /users/current/tags     users/current/tags#index
# 該当ユーザーの全タグ
GET    /users/:user_uuid/tags  users/tags#index
# ランキング用に並べ替えた全タグ
GET    /tags/persistences      tags/persistences#index
GET    /tags/day_counts        tags/day_counts#index
# 一般的なネストしたCRUD
GET    /tags/:tag_id/tweets    tweets#index
POST   /tags/:tag_id/tweets    tweets#create
# 一般的なCRUD
GET    /tags                   tags#index
POST   /tags                   tags#create
GET    /tags/:id               tags#show
PATCH  /tags/:id               tags#update
PUT    /tags/:id               tags#update
DELETE /tags/:id               tags#destroy

参考

Railsのroutingにおけるscope / namespace / module の違い - Qiita

Share on

END
END
@aiandrox

 
目次