Andrew
Andrew

Reputation: 238997

How to constrain a Rails route based on an array of subdomains?

I have a Rails 4.2 application with a set of routes that are constrained to a subdomain.

constraints subdomain: 'admin' do
  # ...
end

However, I'm not sure how to specify multiple subdomains (both admin and admin.staging). How can I specify multiple subdomains?

Upvotes: 4

Views: 2258

Answers (2)

Andrew
Andrew

Reputation: 238997

Even though it's not documented, you can also pass an array of subdomains:

constraints subdomain: ['admin', 'admin.staging'] do
  # ...
end

Upvotes: 14

Jordan Running
Jordan Running

Reputation: 106067

You can use a regular expression, e.g.:

constraints subdomain: /^admin|admin\.staging$/ do
  # ...
end

...or...

constraints subdomain: /^admin(\.staging)?$/ do
  # ...
end

You can also use a lambda:

constraints subdomain: ->(req) { %w[ admin admin.staging ].include?(req.subdomain) } do
  # ...
end

You can read the documentation for constraints here: http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-constraints

Upvotes: 6

Related Questions