Ruby on Rails - Routing



The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. This replaces mod_rewrite rules. Best of all, Rails' Routing works with any web server. Routes are defined in app/config/routes.rb.

Think of creating routes as drawing a map for your requests. The map tells them where to go based on some predefined pattern:

Rails.application.routes.draw do
  Pattern 1 tells some request to go to one place
  Pattern 2 tell them to go to another
  ...
end

Example

Let us conder our library management application contaials one controller that is BookController. we have to define the routes for those actions whicha re defined as methods in the BookController class.

Open routes.rb file in library/config/ directory and edit it with the following content.

Rails.application.routes.draw do
   get 'books/list'
   get 'books/new'
   post 'books/create'
   patch 'books/update'
   get 'books/list'
   get 'books/show'
   get 'books/edit'
   get 'books/delete'
   get 'books/update'
   get 'books/show_subjects'
end

The routes.rb file defines the actions available in the applications and the type of action such as get, post, and patch.

use the following command to list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

rake routes

What is next?

Next we will create the code to generate screens to display data and to take input from the user.

Advertisements