I know about redirecting a specific route:
put 'users/:user_id', to: redirect('/api/v1/users/:user_id')
How would I apply the redirect to all routes generated by resources
? Looking for something like
resources :users, to: redirect('/api/v1')
I can achieve a workaround using match, but it's a bit clunky:
match 'users/*path', to: redirect('/api/v1/users/%{path}'), via: [:GET, :POST, :PUT, :DELETE]
I recently renamed a provider_apps
resource to apps
using the following code, which retains the query params, unlike the solution proposed in the question:
# routes.rb
get 'provider_apps/:slug', status: :moved_permanently, to: redirect { |path_params, request|
query_string = URI(request.url).query
"/apps/#{ path_params[:slug] }#{ "?#{ query_string }" if query_string }"
}
This was inspired by the block example in Rails routing docs . You also have request.query_parameters
available to get a hash of the query params if that's relevant to the destination route.
Maybe try something like this:
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :users
end
end
That'll give you
api_v1_users GET /api/v1/users(.:format) api/v1/users#index {:format=>:json}
POST /api/v1/users(.:format) api/v1/users#create {:format=>:json}
new_api_v1_user GET /api/v1/users/new(.:format) api/v1/users#new {:format=>:json}
edit_api_v1_user GET /api/v1/users/:id/edit(.:format) api/v1/users#edit {:format=>:json}
api_v1_user GET /api/v1/users/:id(.:format) api/v1/users#show {:format=>:json}
PATCH /api/v1/users/:id(.:format) api/v1/users#update {:format=>:json}
PUT /api/v1/users/:id(.:format) api/v1/users#update {:format=>:json}
DELETE /api/v1/users/:id(.:format) api/v1/users#destroy {:format=>:json}
Edit:
namespace :api, path: nil, defaults: { format: :json } do
namespace :v1, path: nil do
resources :users
end
end
That'll give you
api_v1_users GET /users(.:format) api/v1/users#index {:format=>:json}
POST /users(.:format) api/v1/users#create {:format=>:json}
new_api_v1_user GET /users/new(.:format) api/v1/users#new {:format=>:json}
edit_api_v1_user GET /users/:id/edit(.:format) api/v1/users#edit {:format=>:json}
api_v1_user GET /users/:id(.:format) api/v1/users#show {:format=>:json}
PATCH /users/:id(.:format) api/v1/users#update {:format=>:json}
PUT /users/:id(.:format) api/v1/users#update {:format=>:json}
DELETE /users/:id(.:format) api/v1/users#destroy {:format=>:json}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.