LoginSignup
0
0

任意のパスパラメータ名を指定しつつネストしたルーティングをしたい[routes.rb]

Last updated at Posted at 2023-08-23

以下のような3つのAPIを作りたいとき

POST /api/v1/registration_requests
GET  /api/v1/registration_requests/:token
POST /api/v1/registration_requests/:token/accounts

param で指定する

routes.rb
namespace :api, format: :json do
  namespace :v1 do
    resources :registration_requests, only: %i[create show], param: :token do
      resources :accounts, module: :registration_requests, only: %i[create]
    end
  end
end
api_v1_registration_requests         POST /api/v1/registration_requests(.:format)                                      api/v1/registration_requests#create {:format=>/json/}
api_v1_registration_request          GET  /api/v1/registration_requests/:token(.:format)                               api/v1/registration_requests#show {:format=>/json/}
api_v1_registration_request_accounts POST /api/v1/registration_requests/:registration_request_token/accounts(.:format) api/v1/registration_requests/accounts#create {:format=>/json/}

となり、パスパラメータにプレフィックスがついて registration_request_token になってしまう

path で指定する

routes.rb
namespace :api, format: :json do
  namespace :v1 do
    resources :registration_requests, only: %i[create show], param: :token
    namespace :registration_requests, path: 'registration_requests/:token/' do
      resources :accounts, only: %i[create]
    end
  end
end
api_v1_registration_requests          POST /api/v1/registration_requests(.:format)                 api/v1/registration_requests#create {:format=>/json/}
api_v1_registration_request           GET  /api/v1/registration_requests/:token(.:format)          api/v1/registration_requests#show {:format=>/json/}
api_v1_registration_requests_accounts POST /api/v1/registration_requests/:token/accounts(.:format) api/v1/registration_requests/accounts#create {:format=>/json/}

となり、解決!

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