0
0
RailsHow-ToBeginner · 3 min read

How to Create Custom Route in Rails: Simple Guide

In Rails, create a custom route by adding a line in config/routes.rb using HTTP verbs like get, post, etc., followed by the URL path and controller#action. For example, get '/profile', to: 'users#show' creates a custom route to the show action in UsersController.
📐

Syntax

Custom routes in Rails are defined in the config/routes.rb file using HTTP verbs and mapping URLs to controller actions.

  • HTTP verb: get, post, patch, put, delete
  • URL path: The custom URL string you want to match
  • Controller#action: The controller and action method to handle the request
ruby
get '/custom_path', to: 'controller_name#action_name'
💻

Example

This example creates a custom route /profile that routes to the show action in UsersController. When you visit /profile in the browser, it triggers UsersController#show.

ruby
Rails.application.routes.draw do
  get '/profile', to: 'users#show'
end

# In app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    render plain: 'User profile page'
  end
end
Output
User profile page
⚠️

Common Pitfalls

Common mistakes when creating custom routes include:

  • Forgetting to restart the Rails server after changing routes.
  • Using the wrong HTTP verb for the intended action (e.g., using get for a form submission that should be post).
  • Not matching the controller and action names correctly, causing routing errors.
  • Overlapping routes that cause unexpected matches.
ruby
## Wrong way: Missing 'to:' keyword
get '/profile', 'users#show'

## Right way:
get '/profile', to: 'users#show'
📊

Quick Reference

SyntaxDescription
get '/path', to: 'controller#action'Route GET requests to controller action
post '/path', to: 'controller#action'Route POST requests to controller action
patch '/path', to: 'controller#action'Route PATCH requests to controller action
put '/path', to: 'controller#action'Route PUT requests to controller action
delete '/path', to: 'controller#action'Route DELETE requests to controller action

Key Takeaways

Define custom routes in config/routes.rb using HTTP verbs and controller#action syntax.
Use the correct HTTP verb to match the intended request type for your route.
Always restart the Rails server after modifying routes to apply changes.
Ensure controller and action names are spelled correctly to avoid routing errors.
Use the quick reference table to remember common route syntax patterns.