Hello World!

Learn to create custom controllers and views and how they interact with each other.

So far, we have laid the foundation for our application, but we have yet to touch on how to customize its elements. In the tradition of programming, you will do so by making your application display some variant of the phrase “Hello World!”.

Creating a custom controller

To do this, you need a controller and a view. As you may recall, a controller’s purpose is to receive requests for the application. A router decides which controller receives which request.

To create a new controller you need to run the controller generator script in the project root directory my_project/:

rails generate controller Hello index

Running this command will create a controller called “Hello” with an actionActions called “index”.

After the command has finished executing, you can see our controller has been created at the location app/controllers/hello_controller.rb along with a view app/views/welcome/index.html.erb.

Note: You can use rails g as a shorthand for rails generate.

Embedded Ruby

The .erb extension means the file is written in a language called Embedded Ruby. This is the default for the view templates.

In your html.erb files you will be able to use special tags that allow you to embed Ruby code into your HTML. These tags will be processed by Rails, and HTML output will be sent back to the user.

  • <% %>: You can insert any Ruby code between these tags, but the result will not be inserted into your HTML. This tag is used for control flow statements, which we will encounter later.

  • <%= %>: Ruby code between this tag gets inserted into the HTML at its position. This is usually used to retrieve data from models.

Get hands-on with 1200+ tech skills courses.