In a Rails wedding-planner app where each couple gets a subdomain like anna-and-ben.example.com, how do you route those requests with request constraints and a matches? object?
answer
- keys name ActionDispatch::Request methods
- String or Regexp compared with ===
- a symbol value never matches
- matches?(request) or a lambda
- tld_length defaults to 1
basics
~10 sWrap the couple routes in constraints(CoupleSubdomain) do ... end, where CoupleSubdomain.matches?(request) checks request.subdomain. A false answer makes the router fall through to the marketing routes declared below.
solid answer
~40 sA hash such as `constraints subdomain: "www"` calls `request.subdomain` and compares the value with `===`, so it takes a String, a Regexp or an Array of strings; a Symbol like `:www` never matches. Because any couple slug is valid, a fixed value is not enough: use an object that responds to `matches?(request)`, or a lambda, and wrap the couple routes in `constraints(CoupleSubdomain) do ... end` above the marketing site's routes. When it returns false the route passes and the router keeps looking, so `www` and the bare domain reach the marketing pages. Keep the check cheap: it runs on every request that reaches those routes, and the controller can load the couple with `find_by!(subdomain: request.subdomain)`. Finally, `request.subdomain` depends on `config.action_dispatch.tld_length` (default 1), which must be 2 for a domain such as example.co.uk.
code
ruby · 13 lines# config/routes.rb
Rails.application.routes.draw do
constraints subdomain: "admin" do
resources :vendors
end
constraints(CoupleSubdomain) do
get "/", to: "weddings#show", as: :wedding_home
resources :rsvps, only: [:new, :create]
end
root "pages#home"
endgo deeper
Recall the hash form constraints subdomain: "admin" and that values are strings, not symbols.
Explain how hash keys map to request methods, the === comparison, and the matches? and lambda forms.
Show that a false constraint passes to the next route, order the blocks accordingly, keep the check cheap and set tld_length for multi-part TLDs.
Weigh subdomain-per-tenant routing against path prefixes: certificates, cookies, local development and how many routes must stay tenant-aware.
## Two kinds of request constraint Segment constraints test a path segment. **Request constraints** test the request itself: its subdomain, host, IP or anything else the request object knows. Rails offers two shapes: - a **hash** whose keys name methods on `ActionDispatch::Request`, such as `constraints subdomain: "admin"`; - an **object**: anything that responds to `matches?(request)`, or a callable such as a lambda. The wedding-planner app serves its marketing site at `www.example.com` and each couple's site at a slug subdomain like `anna-and-ben.example.com`. A fixed hash cannot express "any slug except www", so this is where an object constraint earns its place. ## How the hash form compares values For each key that is not a path segment, the router calls the request method of that name and compares: | Constraint value | Comparison | |---|---| | String or Regexp | `value === request.subdomain.to_s` | | Array | `value.include?(request.subdomain)` | | `true` / `false` | the result is present / blank | | anything else | `value === result` | Two traps follow from this table: - A **Symbol** never matches: `subdomain: :www` compares `:www === "www"`, which is false. Use `"www"`. - A key that is **not a public method** on the request class is silently dropped when the route is built. A typo such as `subdmain:` does not raise; the route simply matches every host. ## The object form for the couple sites ```ruby # app/constraints/couple_subdomain.rb class CoupleSubdomain RESERVED = %w[www admin].freeze def self.matches?(request) request.subdomain.present? && RESERVED.exclude?(request.subdomain) end end ``` ```ruby # config/routes.rb constraints(CoupleSubdomain) do get "/", to: "weddings#show", as: :wedding_home resources :rsvps, only: [:new, :create] end root "pages#home" ``` Rails accepts anything that responds to `matches?` (a class with a class method, as here, or an instance) or to `call`. A lambda receives the request when it takes one argument, and the path params plus the request when it takes two: `constraints(->(req) { req.subdomain.start_with?("preview-") }) do ... end`. ## What the router does with a false answer 1. A request for `www.example.com/` arrives. 2. The `wedding_home` route matches the path, so the router asks the constraint. 3. `CoupleSubdomain.matches?` returns false, and the endpoint answers internally with a **pass** signal instead of a response. 4. The router moves on to the next matching route, `root "pages#home"`, which serves the marketing page. Because a false constraint passes rather than fails, the **order** of the blocks decides who gets a request, and the constrained routes must come first. ## Keeping the check honest - **Cheap and side-effect free.** The constraint runs for every request whose path reaches those routes. A database lookup there costs a query per request; prefer a shape check and let the controller do `Wedding.find_by!(subdomain: request.subdomain)`, which also gives a clean 404 for an unknown couple. - **The domain's shape.** `request.subdomain` uses `config.action_dispatch.tld_length`, which defaults to 1. On `anna-and-ben.example.co.uk` the subdomain comes back as `anna-and-ben.example` unless you set it to 2. - **Development hosts.** A bare `localhost` or an IP has no subdomain at all, so local testing needs a named host that resolves to your machine, and the host allowlist must permit it. - **Not authorization.** A constraint decides routing. Who may see a couple's page is still the controller's job. ## Hash constraints also shape generated URLs When a hash constraint names a URL part such as `subdomain` with a String value, Rails also uses it as a **default** for generating URLs on those routes. Inside `constraints subdomain: "admin" do resources :vendors end`, `vendors_url` builds `http://admin.example.com/vendors` without being told. An object or lambda constraint gives no such default, so couple links must pass `subdomain:` explicitly. ## Testing subdomain routing Integration tests run against `www.example.com` by default, so a couple route is invisible until the test changes the host: ```ruby test "a couple subdomain reaches the wedding page" do host! "anna-and-ben.example.com" get "/" assert_response :success end ``` Pair it with a test on `www.example.com` that expects the marketing page. Together they pin both branches of the constraint, which is exactly where a reordered routes file or a changed `tld_length` would break.
- Why does constraints subdomain: :api never match in a Rails routes file?The hash form calls `request.subdomain`, which returns a String, and compares it with the constraint value using `===`. `:api === "api"` is false, so the route never matches. Use the string `"api"` or a Regexp. The anchor ban applies only to segment constraints, and a request-constraint Regexp is not anchored for you, so `/\Aapi\z/` avoids also matching a subdomain such as `rapid`.
- Why should a Rails routing constraint object avoid loading the couple record from the database?The constraint runs on every request whose path reaches those routes, before any controller, and its result is not handed to the action. A query there doubles the work, since the controller still has to load the record. Keep the constraint a cheap shape check and let the controller call `find_by!`, which also turns an unknown subdomain into a 404.
- In Rails, what does request.subdomain return for anna-and-ben.example.co.uk with default settings?It returns `"anna-and-ben.example"`, because `config.action_dispatch.tld_length` defaults to 1 and Rails treats only `uk` as the top-level part. Set `tld_length` to 2 so that `example.co.uk` counts as the domain and the subdomain becomes `"anna-and-ben"`.
- constraints subdomain: :www matches the www subdomain
- A false matches? answer makes Rails respond 403 Forbidden
- A misspelt constraint key raises an error when routes load
- request.subdomain knows public suffixes, so co.uk domains need no setting
- Constraint objects must inherit from an ActionDispatch base class