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]
The :as option creates a named path. You can then call this path in your controllers and views (e.g. redirect_to things_path ). This isn't very useful for the root path (as it already named root ), but is very useful for new routes you add.
Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to resources can declare all of the necessary routes for your index , show , new , edit , create , update , and destroy actions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With