0
0
Ruby on Railsframework~30 mins

Route constraints in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Route Constraints in Rails
📖 Scenario: You are building a simple Rails web app that serves different pages based on user roles. You want to restrict access to certain routes so only users with specific roles can visit them.
🎯 Goal: Learn how to use route constraints in Rails to control access to routes based on user roles.
📋 What You'll Learn
Create a custom route constraint class
Add a configuration variable for allowed roles
Use the constraint in the routes file to restrict access
Complete the routes setup with the constraint applied
💡 Why This Matters
🌍 Real World
Route constraints help control access to parts of a web app based on user roles or other conditions, improving security and user experience.
💼 Career
Understanding route constraints is important for Rails developers to implement role-based access control and customize routing behavior.
Progress0 / 4 steps
1
Create a custom route constraint class
Create a Ruby class called UserRoleConstraint with a method matches? that takes a request parameter and returns true if the user role is 'admin'.
Ruby on Rails
Need a hint?

Define a class with a matches? method that checks if request.params[:role] equals 'admin'.

2
Add a configuration variable for allowed roles
Create a variable called allowed_roles and set it to an array containing the string 'admin' and 'manager'.
Ruby on Rails
Need a hint?

Use an array allowed_roles and check if request.params[:role] is included in it.

3
Use the constraint in the routes file
In the config/routes.rb file, add a route get '/dashboard' that routes to dashboard#index and uses the constraint UserRoleConstraint.new.
Ruby on Rails
Need a hint?

Use get '/dashboard', to: 'dashboard#index', constraints: UserRoleConstraint.new inside the routes.draw block.

4
Complete the routes setup with the constraint applied
Add a root route root to: 'home#index' without constraints below the constrained route in config/routes.rb.
Ruby on Rails
Need a hint?

Add root to: 'home#index' inside the routes.draw block after the constrained route.