`

# What are shallow routes?

210

 Shallow routes in Rails are a way to simplify nested resource routes by reducing the depth of the URL structure for certain actions. This makes the URLs shorter and more readable, especially when dealing with deeply nested resources.

How Shallow Routes Work

When you use shallow routes, only the routes for creating new resources and listing resources are nested. The routes for showing, editing, updating, and deleting resources are not nested.

Example

Consider a scenario where you have users and posts, and each user has many posts. Without shallow routes, the routes might look like this:

resources :users do
  resources :posts
end
This would generate routes like:
  • /users/:user_id/posts (index)
  • /users/:user_id/posts/new (new)
  • /users/:user_id/posts/:id (show)
  • /users/:user_id/posts/:id/edit (edit)
  • /users/:user_id/posts/:id (update)
  • /users/:user_id/posts/:id (destroy)
With shallow routes, you can simplify this:

resources :users, shallow: true do
  resources :posts
end
This would generate routes like:
  • /users/:user_id/posts (index)
  • /users/:user_id/posts/new (new)
  • /posts/:id (show)
  • /posts/:id/edit (edit)
  • /posts/:id (update)
  • /posts/:id (destroy)
Benefits of Shallow Routes
  1. Shorter URLs: The URLs are shorter and more readable.
  2. Simplified Controllers: Controllers can be simpler because they don’t need to handle deeply nested parameters.
  3. Improved Performance: Shorter URLs can lead to slightly improved performance due to less parsing.
When to Use Shallow Routes

Shallow routes are particularly useful when the nested resource can be uniquely identified without the parent resource. For example, a post can be uniquely identified by its ID without needing the user_id.

Example in Practice

Rails.application.routes.draw do
  resources :users, shallow: true do
    resources :posts
  end
end
This setup allows you to access a post directly via /posts/:id without needing to include the user ID in the URL.