0
0
Ruby on Railsframework~5 mins

Route constraints in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aget '/posts', to: 'posts#index', match: 'json'
Bget '/posts', to: 'posts#index', format: 'json'
Cget '/posts', to: 'posts#index', constraints: { format: 'json' }
Dget '/posts', to: 'posts#index', only: 'json'
What method must a custom constraint class implement in Rails?
Acall
Bmatches?
Ccheck
Dvalidate
If a route constraint returns false, what does Rails do?
ARaises an error
BRedirects to the homepage
CStops routing and returns 500
DSkips the route and tries the next one
Which of these can be used as a route constraint in Rails?
AAll of the above
BA custom class with matches? method
CA regular expression
DA hash with key-value pairs
Why use route constraints in a Rails app?
ATo restrict routes based on request details
BTo improve route matching speed
CTo style routes with CSS
DTo generate database queries
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.