How To Create a "Hello World" App in Ruby on Rails 6.1

We’ve so far covered creating a “Hello World” app using just the Rails API and also by integrating Rails with React but in this post we’re going to cover the standard, or “vanilla” approach by using views.

Creating a Project

Similar to what we’ve done in the earlier posts in this series, we will use the rails new command to create a new project. However, since we’re going to create a standard Rails app we will not use any special flags:

1
rails new hello_world

If you start the server and navigate to localhost:3000 you’ll see the familiar landing page. If you’ve read the previous posts, you’re probably guessing what we have to do next. Create a controller!

Creating a Controller

Hopefully this is becoming a little clearer as we go on but just to restate, we need to create a controller, which is a Ruby class that contains one or more methods, also referred to as actions. When run, this method will then fire off a view, which is a template that contains HTML and possibly some Ruby.

While we could create the controller and route separately by using the --skip-routes flag, it’s easier to have Rails take care of both for us as well as create the view for this controller. So let’s just run the following code:

1
rails generate controller hello_world index

This will create a controller with the file name hello_world_controller.rb and a method called index. It will also create a view with the same name as this method in our views folder.

Since we want the “Hello World” message to appear when we visit localhost:3000, or in other terms, the “root” of app, we need to make sure the routes file reflects this.

Create a Route to Root

Similar to how we did it in the previous post, we need to open the routes.rb file in the config directory and change it to the following:

1
2
3
Rails.application.routes.draw do
root 'hello_world#index'
end

Remember how the generate command created a view for our index method automatically? All that’s left is to change it to reflect the text we want.

Modify the Index View

Open the index.html.erb file and replace it with the following:

1
<h1>Hello World!</h1>

Now, just give localhost:3000 a refresh and you should see this:

All done!

Conclusion

Well that wraps up this series of posts on how to write a “Hello World” Rails app in three different ways. Each way illustrated a different implementation of Rails.

  1. Using Rails as a back-end only
  2. Using Rails as a back-end paired with React
  3. Using Rails as a full framework

See you at the next post!