Recall & Review
beginner
What is a route constraint in Rails?
A route constraint is a rule that limits which requests match a route. It helps control routing by checking conditions like request parameters, formats, or custom logic before choosing a route.
Click to reveal answer
beginner
How do you apply a simple format constraint to a route in Rails?
You add
constraints: { format: 'json' } to the route. This means the route only matches requests asking for JSON format.Click to reveal answer
intermediate
What is the purpose of a custom constraint class in Rails routing?A custom constraint class lets you write Ruby code to decide if a route matches. It must have a <code>matches?</code> method that returns true or false based on the request.Click to reveal answer
intermediate
Example: How to restrict a route to only match if a user is an admin using a constraint?
Create a class like <code>AdminConstraint</code> with a <code>matches?</code> method checking if <code>request.session[:user_role] == 'admin'</code>. Then use <code>constraints AdminConstraint.new do ... end</code> around the route.Click to reveal answer
beginner
What happens if a route constraint returns false for a request?
Rails skips that route and tries the next one. If no routes match, it returns a 404 Not Found error.
Click to reveal answer
Which of these is a valid way to add a format constraint to a Rails route?
✗ Incorrect
Option C correctly uses the constraints hash to limit the route to JSON format.
What method must a custom constraint class implement in Rails?
✗ Incorrect
The custom constraint class must implement the matches? method that returns true or false.
If a route constraint returns false, what does Rails do?
✗ Incorrect
Rails skips the route and tries the next matching route if the constraint returns false.
Which of these can be used as a route constraint in Rails?
✗ Incorrect
Rails supports regex, custom classes, and hashes as route constraints.
Why use route constraints in a Rails app?
✗ Incorrect
Route constraints restrict which requests match a route based on conditions like format or user role.
Explain how to create and use a custom route constraint in Rails.
Think about how to check request details before routing.
You got /4 concepts.
Describe what happens when a route constraint does not match a request.
Consider the routing process flow.
You got /3 concepts.