Any web app has routes. A route is a mapping from a url to your ruby code. Each url endpoint can link to part of your ruby code.

Examples of routes can be /admin/, /users/, /stats/ after your domain name.

If you haven’t created a rails app yet, type rails new blog.

Routes

Routes

All Routes for a Rails web app are defined in /config/routes.rb. By default the file is doesn’t define routes:

1
2
3
Rails.application.routes.draw do

end

You can add new routes here. Lets add one.

1
2
3
Rails.application.routes.draw do
get 'hello' => 'hello#index'
end

This maps the url ‘/hello/‘ to the ruby code (controller) ‘HelloController’. The addition #index is the method that will be called, which exists even if not defined.

Controller

The first word hello/ is the name of the controller.
Create it with the line:

rails generate controller hello index

Then you’ll have the file hello_controller.rb in /app/controllers/, with this contents:

1
2
class HelloController < ApplicationController
end

View

Create a view in /app/views/hello/. If the directory doesn’t exist, create it. The view file should end in .erb, but it contains html code.

In /app/views/users/ you should have index.erb with this contents:

<h1>Hello World</h1>

Result

Start the app with rails server.

Open the link /hello/ to see the message Hello World.

The controller HelloController, returns the view /app/views/hello/index.erb.

Debugging

If you get the error

Routing error - uninitialized constant

It may be a filename error. The filename must match the class name.

The file app/controllers/hello_controller.rb should contain class HelloController.