Kieran E
Kieran E

Reputation: 3666

Automatically generating scoped and unscoped Rails routes

We have a tenant-like application that specifies many tenant and general routes for the same controller/action. As an example:

get '/:subdomain/posts', to: 'posts#index'
get '/posts', to: 'posts#index'

As you can imagine, this gets cumbersome when many routes share this behaviour. I'm trying to design a module that can be included in the routes file that would let me specify routes like so:

general_and_tenant_scope do
  resources :posts
  resources :users
end

And have it automatically map to something like this:

scope '/:subdomain', as: :tenant do
  resources :posts
  resources :users
end

resources :posts
resources :users

Upvotes: 1

Views: 117

Answers (1)

Kieran E
Kieran E

Reputation: 3666

You can do this by creating a helper like so:

def general_and_tenant_scope(&block)
  scope('/:subdomain', as: :tenant, &block)

  yield
end

You may be able to include this as a helper by employing a technique outlined here, but we simply put this at the top of our routes.rb.

Upvotes: 1

Related Questions