params[:id]?Rails.application.routes.draw do get '/items/:id', to: 'items#show', constraints: { id: /^\d{3}$/ } end
The route constraint /^\d{3}$/ means the :id must be exactly three digits. So '/items/123' matches and sets params[:id] to '123'. Other options either have letters or wrong digit counts, so they don't match.
Option A correctly uses a Ruby regular expression /[a-z]+/ inside a hash for constraints. Option A is missing braces and uses a string instead of Regexp. Option A uses a string instead of Regexp. Option A uses uppercase letters which is incorrect for lowercase only.
get '/products/:code', to: 'products#show', constraints: { code: /\d{4}/ }
Why does the URL '/products/12345' still match this route?The regex /\d{4}/ matches any substring of four digits anywhere in the string. Since '12345' contains '1234' at the start, it matches. To fix this, anchor the regex with ^\d{4}$ to match exactly four digits.
get '/archive/:year', to: 'archive#show', constraints: { year: /\d{4}/ }
And the URL '/archive/2023', what is the value of params[:year] inside the controller?Route parameters in Rails are always strings. Even if the constraint matches digits, params[:year] will be the string '2023'.
Rails allows route constraints to be a class or object that implements a matches?(request) method. This lets you write complex logic to decide if a route matches. Constraints are checked before the controller action runs. They cannot modify params directly.