4
5

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 3 years have passed since last update.

【Rails】複雑なルーティング構成まとめ

Posted at

今回は、Usersリソースを中心に、追加構成としてAPIディレクトリを追加してみたり、新たなメソッドとしてsortメソッドを追加したときのパスの状態などを設定するパターンで見ていく

#早見表

種類 パス クラス ファイルパス
scope /api/users UsersController /users_controller.rb
namespace /api/users Api::UsersController /api/users_controller.rb
module /users Api::UsersController /api/users_controller.rb
member /users/:id/sort
collection /users/sort

#Controllersのディレクトリ構成と、ルーティング

##scope

routes.rb
# /api/users

scope :api do
  resources :users
end
ディレクトリ構成
/controllers--
            |
            |--application.rb
            |
            |--users_controller.rb
controller.rb
class UsersController < ApplicationController
end

##namespace

routes.rb
# /api/users

namespace :api do
  resources :users
end
ディレクトリ構成
controllers/-
            |
            |--application.rb
            |
            |--api/-
                   |
                   |--users_controller.rb
controller.rb
class Api::UsersController < ApplicationController
end

##module

routes.rb
# /users

scope module: :api do
  resources :users
end
ディレクトリ構成
controllers/-
            |
            |--application.rb
            |
            |--api/-
                   |
                   |--users_controller.rb
controller.rb
class Api::UsersController < ApplicationController
end

#まったく新しいパスを作る

##member

routes.rb
# idを伴うパス /users/:id/sort

resources :users do
  member do
    get :sort
  end
end

省略形

routes.rb
resources :users do
  get :sort, on: :member
end

##collection

routes.rb
# idを伴わないパス /users/sort

resources :users do
  collection do
    get :sort
  end
end

省略形

routes.rb
resources :users do
  get :sort, on: :collection
end

#参考記事

https://qiita.com/senou/items/f1491e53450cb347606b

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?