Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes: redirect an entire resource

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]
like image 989
Elise Avatar asked Jun 06 '16 13:06

Elise


People also ask

What does as do in Rails routes?

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.

What is the difference between resources and resource in Rails?

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.

What are Rails resource routes?

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.


1 Answers

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.

like image 113
wbharding Avatar answered Sep 20 '22 13:09

wbharding