Routes in Ruby on Rails 5: how you can use resources and records to define URLs

Written by Ryan Davidson.

The starting point is config/routes.rb, where you specify the routes for Ruby on Rails to find your pages.

Ruby on Rails has a set of pre-built helper methods to create routes for web pages in your application. While they can be simple to get started, they can be configured to generate a range of customisable routes and pages for your web app.

Where to configure your routes

config/routes.rb is where you specify the routes for your Ruby on Rails application. This tutorial will show you how to add to this file to define your routes using both helper methods and more customised options.

The root Route

The method root defines where Rails should direct to the route / , for example google.com/ .

You should put the root route at the top of the config/routes.rb file, because it is the most popular route and should be matched first. — Rails Guides: Routing

You can specify any page you want here, for example:

Rails.application.routes.draw do 
  root 'posts#index'
end

Or set it via a controller:

root controller: :post, action: :index

Within any controller, you can then redirect back here by using the method redirect_to root_path.

root_path. Image source.

Resources

It’s a lot of work having to define each route in your website. So Rails provides helper methods called resources . A singular resource can be specified for a specific route:

get 'profile', to: 'users#show'

get 'profile', to: :show, controller: 'users'

If you generate a model and controller, such as Suggestion, you can generate multiple routes by adding resources :suggestion in the config/routes.rb

The rails helper methods and urls generated by resources :suggestion

Now in your controller or view you can use these helper methods to direct the routes.

redirect_to suggestion_index_path

Will go to:

class SuggestionController < ApplicationController
def index
@geocoders = Geocoder.all
end
end

You can also specify just the ones you need by following the resources command with an array of just the pages you want, such as:

resources :suggestion, only: %i[new create show destroy]

By default, Rails sets the URL of a record by its ID, for example suggestion/1 for the first record. But resources can override this. You can provide other types of URLs, such as those defined by the a page’s slug (short description of the page) by using:

resources :tip, only: %i[index new create show destroy], param: :slug
For more on using descriptive URLs see my post:
- Custom urls in Ruby on Rails: use descriptive slugs instead of ids
Route. Image source.

Using records for routing

Instead of having to remember or write out the route associated with a record, Rails translates an ActiveRecord instance into a route.

@patient = Patient.find(17)

You can then use the record variable in a view to be rendered into HTML in the browser.

<%= link_to 'Patient Record', patient_path(@patient) %>

The router will generate the path /patients/17 , without having to specify the record id. The record variable can also be easily changed in the controller without needing to update the path in the view.

This can also be used for post events, such as delete.

<%= link_to 'Destroy',  @post,  method: :delete, data: { confirm: 'Are you sure?' } %>
You can mark your paths using records. Image source.

Redirections and Misdirections

Redirections are done by specifying the method, target page, and the redirect helper method.

get '/stories', to: redirect('/articles')

If a page isn’t found, some websites render a page for a 404 response error. But with Rails you can set a default route for this scenario. In the below example, place this line at the end of the routes.draw block.

Rails.application.routes.draw do
# ... all your other routes
match "*path", to: "application#index", via: :all
end

Then, if you wanted to include a message to let the user know the page wasn’t found:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
  def index
flash.notice = 'No page found at that address'
redirect_to root_path
end
end

Read more from Ryan Davidson

Read more from the web


Routes in Ruby on Rails 5: how you can use resources and records to define URLs was originally published in freeCodeCamp on Medium.