0
0
Ruby on Railsframework~5 mins

Route constraints in Ruby on Rails

Choose your learning style9 modes available
Introduction

Route constraints help control which URLs match specific routes. They make your app respond only to certain patterns or conditions.

You want to allow only numeric IDs in a URL segment.
You want to restrict routes to certain subdomains.
You want to match routes only if a request header or parameter meets a condition.
You want to separate admin routes from user routes by URL pattern.
You want to handle different formats like JSON or HTML based on URL.
Syntax
Ruby on Rails
get '/path/:id', to: 'controller#action', constraints: { id: /\d+/ }
Constraints can be regular expressions or objects responding to `matches?` method.
You can apply constraints to parameters, subdomains, or the whole request.
Examples
This route only matches if :id is all digits.
Ruby on Rails
get '/products/:id', to: 'products#show', constraints: { id: /\d+/ }
This route matches only if the subdomain is 'admin'.
Ruby on Rails
constraints subdomain: 'admin' do
  get '/dashboard', to: 'admin#dashboard'
end
This route matches only if the user is logged in (session has user_id).
Ruby on Rails
get '/profile', to: 'users#profile', constraints: lambda { |req| req.session[:user_id].present? }
Sample Program

This example shows two routes: one that only matches numeric IDs for items, and another that only works if the subdomain is 'admin'.

Ruby on Rails
Rails.application.routes.draw do
  # Route only matches numeric IDs
  get '/items/:id', to: 'items#show', constraints: { id: /\d+/ }

  # Route only matches subdomain 'admin'
  constraints subdomain: 'admin' do
    get '/dashboard', to: 'admin#dashboard'
  end
end
OutputSuccess
Important Notes

Use regular expressions carefully to avoid blocking valid URLs.

Custom constraint objects can give more control by implementing a matches? method.

Test your routes with `rails routes` and try URLs in the browser or console.

Summary

Route constraints limit which URLs match routes based on patterns or conditions.

You can use regex, subdomains, or custom logic for constraints.

They help keep your app organized and secure by controlling access paths.