Ruby on Rails for Complete Beginners

Felix
The Blog of Felix Oginni
25 min readJun 30, 2016

--

So far, over 4128 people have started my Coding Founders course (Learn Ruby on Rails by Cloning ProductHunt).

The first part of the course gives you a thorough introduction to Ruby on Rails and my students loved it so much, that I decided to turn it into a book.

Below is the first chapter (which you can also download for offline reading here).

I’ll be releasing about one chapter per week as I write them (I’ll update this page and gumroad as I write every week).

Enjoy

Chapter 1 — Rails Basics

Installing Rails

What I used to do when I taught this course in the past was that I’ll take a new computer that doesn’t have rails on it and go through the process of installing rails so my students can follow along.

The problem is, if anything changes in the whole process (which happens a lot), the tutorial would break and it won’t be useful to you any longer.

So what I do now, is just teach you how to learn how to install rails on your own, so you can go through the process on your own, regardless of what computer you are on, or whatever changes in the process that might have occurred.

Rails on Windows

A warning. I use a Mac, I have used Linux before and I have also used windows for rails development. I don’t recommend windows for rails development. It’s a painful experience. Use windows if it’s your only choice. If it isn’t, find something else.

If you must use windows, I recommend using Nitrous.io. It’s a development environment that lives in the cloud (in your browser) not on your computer, so you wont be exposed to all the native errors that make windows such a pain to develop with on windows.

If you are stubborn however and you feel you must use Windows natively for your rails development, it’s not actually that bad, you’ll survive.

To install rails on windows (You Stubborn! Stubborn! Child):

Step 1 — Type “Railsbridge Installfest windows” into Google

The website looks like this.

Follow the instructions step by step and you’ll have everything you need to work with rails installed for you at the end.

Note: We are going to work with Github and Heroku later (don’t worry about what they are right now).

When you setup git and ssh (step 2 with this tutorial), remember the email address and passwords you use, so we can use them with Github and Heroku later.

Rails on the Macbook and Linux

Type in “Install Rails Mac” in Google and follow the link that leads to gorails.com. They have a very good mac installation guide for ruby on rails and they keep it quite updated.

There, select your operating system and follow their instructions (if you are on Linux, click Ubuntu and follow those instructions).

Note: Ignore the “setting up the database” section. We’ll use the default sqlite that comes with Rails and when we deploy to production, Heroku automatically configures Postgre SQL for us, so you don’t need this headache.

Install Heroku

Hopefully, you now have a working installation of Ruby, Rails and Git. If you do, It’s time to install Heroku.

Google “Heroku Toolbelt” and click on the first link.

Then just select your operating system, download and install. Before you install, I recommend you first create an account with Heroku and sign in, then come back to this page to download and install the Heroku toolbelt.

Install Sublime Text

We need a text editor to write and edit our Ruby/Rails code. My favourite text editor for Rails programming is Sublime Text. Of course, you can use any text editor you desire, but if you have no preference, I recommend this one.

Download it free at: https://www.sublimetext.com/ or just Google “Sublime Text”. I promise, you’ll fall in LOVE.

Generate and run a new Rails APP

So let’s go ahead and generate a new rails application. To do this:

· Open up your terminal

· Cd into your desktop (type cd Desktop and press Enter)

· And then generate a new rails application with the following command (rails new myblog)

With that, Rails will go ahead and generate a new rails application for us, with all the files, folders and everything we need to make our application work and we are just going to customise this to fit our particular use-case which in this case, is to make a blog.

On your desktop, you’ll see that Rails has created what will become our blog app (myblog), so let’s cd into this directory and use the subl command to open the app in our sublime text (our text editor), so we can start making some changes.

Cd myblog

Subl .

Now you have the myblog application open in Sublime Text, you’ll find all the files and folders Rails created for us on the left hand side. This is just a starting point. Rails laid a foundation for us and now we have to build our proverbial house (our app) on top of it.

Now let’s run our application and check it out in the browser. To start your rails server, you need to use the rails s command which is short for rails server. Both commands (“rails s” and “rails server”) will start the Rails application and make it available in your browser at localhost port 3000.

Rails s.

So if we now head over to your browser and type in “localhost:3000”, you’ll get direct access to your web application. This is where we are going to test most of our code and check that everything we are doing is actually working.

The page you are seeing is the default welcome page, to show you that everything is all setup properly and you are all set to start coding. We’re going to replace this page with the homepage of our application when we build it.

To kill the server, press the commands ctrl + c

Ctrl + c

And that will kill the server. Of course, you can use rails s to start it up again.

Rails Files and Folders

The long list of files and folders on the left side of your text editor can seem a bit intimidating at first. I’ll take a few minutes to introduce you to the important folders but as we build a web application Rails, you’ll get familiar with it.

The App Directory

The App directory which is expanded in the screenshot above, is by far the most important. This is where most of your code will go.

Of all the folders in this App directory, the Controller, Models and Views are the most important. I’ll explain what they do in detail much later. The assets are where your Images, Javascript files and Stylesheets will go.

The Config Directory

This is the second most important directory here. The important files inside here are

1. Routes.rb — This is where you’ll map URL Requests (like yoursite.com/pages) to the correct controller/action that will deal with that request.

2. Database.yml — this is your database configuration file. We’ll get to this later.

The other file you’ll use a lot is the Gemfile. This is where we’ll install Ruby Gems. Ruby Gems are pre-written code libraries that bring in extra functionality into our App so we don’t have to write the code ourselves.

Good ruby gems will save you time as there is no need to re-invent the wheel if someone has already done the work for you. That said, don’t get dependent on Gems. Use them sparingly and only when absolutely necessary, especially as you learn.

MVC Architecture.

Rails uses the MVC architecture to arrange your code. From Wikipedia: “It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented”.

This makes large applications easy to work with. The diagram above illustrates how this works in practical terms.

How It Works

When your Rails application gets a HTTP request from the browser (for example when you visit google.com, what you did was send a HTTP request to the google servers for the google.com page), Rails directs this request first to the Router as shown in the diagram above. Here’s what the router looks like.

It’s the routes.rb file in your Rails application (It’s inside the config folder):

The router decides which controller will process that request and passes the request along to the controller. The controller will do it’s processing and figure out whether it needs any data from the database.

If it does, It’ll talk to the model and the model will retrieve that data from the database and send it to the controller. It just keeps going back and forth like this until it has everything it needs to serve that HTTP request.

Once it gets everything it needs, it passes that data along to the views, inserts that data into the view templates (using erb tags — you’ll learn about this later) and after assembling the data into the view templates, it sends the page to the browser (as a HTTP Response, with HTML, CSS and Javascript files where necessary) and the browser renders the page you requested once it receives these files.

This is how Rails handles server requests:

Browser (HTTP request) -> Router -> Controller -> Model -> Database -> Model -> View -> Browser (HTTP response).

This is how everything works. Model. View. Controller. Simple right?

Generate a Controller

Now let’s go ahead and build an About us and a Contact us page for out blog. To do this, we need to generate a controller.

Open your Terminal and CD into your “myblog” directory. Depending on what directory your terminal is in right now, you should:

Cd Desktop

Cd myblog

So what we want to do now is to generate a controller that will handle the requests for our about and contact us pages.

I’m going to call it the “pages” controller. To generate this controller, we use the rails g controller command in the terminal, but before we do this, I’m just going to type rails g (short for “rails generate” which also works) and press enter.

Rails g

When you type the rails g command without any instructions after it, Rails will tell us exactly how to use this generator. So if you ever forget the exact syntax to use to make any Rails generator or command work, just type it in without instructions and press enter. And rails will tell you how to use it.

So in this case, by typing rails g,

Rails shows us all of the generators we have available. In this case, we want to generate a controller.

So let’s go ahead and type “rails g controller” in the terminal, without passing any options, so rails can tell us how to use the controller generator:

Rails g controller

As you can see, Rails tells us exactly how to use this generator. In this case, we need to pass the name of the controller (which is required) and if we want it to generate action for us (this is optional), we pass in the names of the actions we want it to create. We can also pass in special options after the action name.

We are not going to pass in any actions right now. We’ll do that manually later on (oh and if you don’t know what actions are, I’ll explain that soon).

In the example above, CreditCards is the name of the controller you want to generate, and then open, debit, credit and close are the actions that will be created in that controller.

Now before we move on, I want you to pay special attention to the way the controller is named. Controller names are written in CamelCase and Pluralised. Models on the other hand (which we’ll talk about later) are singular and lowercase.

So in the example above, the corresponding model would be named creditcard. This is Rails’ convention.

Camel case means that you capitalize the first letter of every word in the name, but don’t add any spaces between the names because anything after the first space but before the options would be taken as an action.

Now let’s create a controller to hold our About and Contactus pages. So we run the following command in our terminal

rails g controller Pages

As I said before, I could go ahead and create the about and contactus actions by adding them to the command above, but I’m not going to do that, so I can show you how to do it manually.

As you can see from the terminal, R ails has generated a controller for us, with a files to hold the Stylesheets, Javascript and Helpers that correspond to this controller. I’ll explain what helpers are much later. Ignore the test units as that is beyond the scope of this course.

Now let’s head over to Sublime Text and open the Controller Folder and pages_controller.rb file (the pages controller).

As you can see, Rails has generated an empty controller for us. You can create all these files manually of course(and as you get more comfortable with rails, you’ll do this sometimes).

The generator is just a faster way to do it, especially when we need all the extra files it creates (like the css and js files).

In the next section, we are going to fill out the controller with the two actions that we need to process incoming requests for the About and the ContactUs pages.

Create the About Page

Okay so now we have a controller and our controller is empty.

By the way, as you can see, a controller is pretty much just a Ruby class that Inherits functionality from Application Controller. That’s it.

So if we go ahead and create what we call an Action in rails, you are actually just creating a Ruby method. But in Rails, we call a Ruby Method that reside in the controller an “Action”.

So actions are just Ruby Methods inside Controllers (and the controller is just a class that inherits from ApplicationController).

This stuff is so easy right?

So let’s create two methods (actions) inside this Pages Controller. We’ll call the first one About and the second one contact.

So we now have an action for the about page, and another for the contact page.

The about action will handle the processing of the HTTP requests for the about page, and the contact action will do the same for the contact page.

So what do we know now.

We created a controller, we created two actions and we know that actions are just ruby methods inside a class (called controller) that inherits from ApplicationController.

So let’s start by creating the About Page.

Let’s go to the browser and see if we can find the About Page, even though we haven’t created it yet.

We are in the Pages controller and we are looking for the about action (the action that will handle the request for out about page), so we head over to localhost:3000/pages/about.

When we do this, we get an error:

It says “routing error”. We know from the MVC architecture that each request first goes to the router in Rails, but this error is telling us that we don’t have any instructions in the router for how to deal with a request for /pages/about, so it doesn’t know what to do with this request.

So let’s go ahead and tell it what to do. To do this, we head over to the routes.rb file (inside the config folder) and tell the router to direct this request to the pages controller and the about action inside that controller.

In your routes.rb file, type the following (line 2):

get

get indicates that the router should listen for a get request to that path (pages/about). A get request is a type of HTTP request, that the browser uses to ask for information from the server. The browser uses a post request to send information to the server. We also have PATCH (used to update objects in the server) and DELETE used to remove objects.

Now back to our app.

The line

get “pages/about” => “pages#about”

instructs Rails to direct any get request for “pages/about” to the pages controller and the about action.

Now Rails knows how to process the request for “pages/about” so if we head back to the browser and refresh, let’s see what happens:

As you can see, we get a different error (Which is good. When your errors change, it usually means you are making progress). This time, it says “Template is missing”.

What’s happening here?

Well, Rails now knows half of the story. It knows where to direct the request for “pages/about” and it sends the request to the about action in the pages controller for processing (I think might have repeated this 100 times now. Forgive me.) but if we take a look at the action, you can see it’s empty because we haven’t put any instructions in there yet.

The default behavior in Rails is that if the action is empty, it just tries to render a view template with the same name as the action. It first looks in the views folder for a folder that matches the name of the controller, then inside this folder, it looks for a view template matching the name of the action.

You should note that even if the action is not empty (i.e, if it has code inside of it), after the action is done with its processing, it’ll still try and render this view template if you don’t specifically instruct it to render something else or redirect somewhere else.

Also, the pages folder (inside the views folder) was generated for us when we generated the controller. If we had passed in actions to the generator when we created the controller, it would have made corresponding view templates for us as well but don’t worry, we’ll do that ourselves in one second.

For now, create a new file and save it in the pages folder that’s inside the views folder. Name this file about.html.erb.

.html specifies that it’s a HTML view template that you are trying to create and .erb means that it’s an erb file. Erb means Embedded Ruby and from its name, it should be clear that it .erb files allow you to embed Ruby code in them.

Open up this file and let’s add some HTML code to it, so we can view it in the browser and see if what we have done so-far has worked.

Just add one line of code (a <h1>) that says “Hi, welcome to the about page” like so:

Now let’s head back to the browser and you’ll see that finally, Rails is able to display the page we requested (pages/about). Phew!

So let’s recap a little bit and go over what we just did:

· First, we generated a pages controller with the command (rails g controller Pages)

· Then we created two actions in the controller, one for the about page and one for the contact page.

· We went to routes.rb to tell the Rails where to route (direct) a get request for our about page (get “pages/about” => “pages#about”)

· Then finally, we created an about.html.erb view template in the pages folder (inside of the views folder), so Rails has something to respond to our request with.

· We added a line of HTML to our view template, just so we could see something in the browser

· And finally we opened this page up in the browser and everything worked as expected.

Nice work! Now your task is to go ahead and repeat this process for the contact action. Your goal is to render a page that shows “Hi, welcome to the contact page” in the browser when we visit localhost:3000/pages/contact.

My reputation is on the line here. You MUST do this (otherwise I’m a bad teacher and that’ll make me sad L ). So, do it for me?

Instance Variables vs Local Variables (and Embedded Ruby)

Now if you’ve done any Ruby before, you’ll know that we have a few types of variables. Hopefully, you know enough programming to know what variables are.

The two types of variables most relevant to you as a Rails developer, are Instance Variables and Local Variables.

Local variables are written “as is” and Instance Variables start with an @.

Let’s head over to the controller and in the contact action, create and assign the string “My Name is Felix” to an instance variable @felix.

On the next line, assign the same string to a local variable felix. Feel free to replace “Felix” with your first name.

So on line 7 we have an instance variable with a string assigned to it and on line 8, we have a local variable with the same string assigned. Now you know what each one looks like.

In the context of Ruby on Rails, the main difference between an instance variable and a local variable is that the Instance Variable is available in the Views.

To illustrate this, copy line 7 (@felix = “My name is Felix”) and move it to the about action.

Let’s pause here for one second and head over to the about.html.erb view template and talk a little about Embedded Ruby.

Embedded Ruby

Now as I told you earlier, Embedded Ruby allow you to embed Ruby code into your view templates. These are the two .erb tags that you can use to make this happen:

1. <%= your ruby code goes here %>

2. <% your ruby code goes here %>

As you can see, they are pretty much identical, leave for the = sign at the beginning of the first one.

The only difference between these two .erb tags, is that the first one (with the = sign) outputs the evaluation of the Ruby code inside of it, into the page. The second one doesn’t and as we go through this course, you’ll get to see exactly how that works.

When a view is invoked, Rails first parses the document, evaluates the Embedded Ruby code inside of it before starting the process of rendering the view template.

Okay now let’s head back to our controller.

We have a local variable in our contact controller and an instance variable in out about controller.

So if we open up contact.html.erb, insert a <p> element and inside of that element we put an erb tag <%= %>. We’re using this erb tag because we want the result outputted in the page.

Inside that erb tag, let’s try and call the local variable “felix” from the controller.

Now let’s head over to the browser and see what happens.

As expected, we are getting an error. It says NameError in pages#contact and it also highlights that error for us, which is on line 3.

We get this error because as we mentioned earlier, local variables from the controller are not available in the view templates. So as far as Rails is concerned, if you are in the view, this local variable (that you declared in the controller), does not exist.

Okay.

If we head back to the pages controller and change that to an instance variable by adding an @ in front of it like so:

Now let’s head back to our contact view template and update that as well:

Now if we head back to our browser

You’ll see that the page now renders properly, with the string “My Name is Felix” coming directly from the controller.

Render

When your browser requests a page from Rails (say “pages/about”), that request goes first to the router, which directs it to the controller and the controller tries to use the “right” view template to render the page. You know this already.

Now this is Rails’ default behavior and as with any other thing in Rails, this default behavior is customizable.

So for example, when it gets to the about action, you can tell Rails to ignore about.html.erb and instead, use contact.html.erb to render the requested page.

So if we go ahead and delete about.html.erb,

when we head back to the browse, we’ll see the template is missing error that we saw earlier (before creating the page).

Instead of creating this page again, we can tell Rails to use another view template — the contact.html.erb view template for example — to render this page.

All you do is type render and the name of the action (as a symbol), who’s view template you’ll like it to render.

So if we wanted the about action now to use the contact.html.erb view template to render the page, we would type the following

and it’s going to go ahead and use the contact.html.erb view template (the view template corresponding to the contact action) to render this page.

Notice we typed :contact. This is called a symbol in ruby.

So if we head back to the browse, you’ll see that the contact.html.erb view template is now being used to render the about page.

So with the render command, you can change Rails’ default behavior and use any view template that you have to render the page in the browser. You’ll see why this is useful in the next chapter.

Link Helper

Now let’s just take line 4 out of our controller (remove the render line)

and return our about.html.erb view template (create another one) and return the <h1> that says “This is the about page” like so:

Now let’ s talk a little bit about helpers.

I’ve mentioned helpers before (while explaining the Rails folders). Helpers go in the hhelpers folder (just below controllers and above mailers in the screenshot above).

If you remember, .erb lets you Embed Ruby code into your view templates, but it’s always a bad idea to have too much code in your views. You should always aim to have as little code as possible in the views and when you have something that you might want to repeat a few times, you should extract that code and place it in the helper, so you can just call it from the views when you need it.

When we generated our pages controller, Rails generated a pages helper for us. This helpers concept might seem a bit abstract now but I have an example later in the book that illustrates the concept perfectly, so hold tight.

We’ll write our own custom helpers in a bit but for now, let me introduce you to two of them right now. I’ll start with the Link Helper.

The Link Helper

You should already know that with HTML, we can link pages together. This is one of the fundamental concepts that make websites work the way they do.

So if we wanted to link the about and contact us pages together, we could add two links in each one of the pages.

and the links would appear in the browser like so:

So far, so good.

Building links in Ruby on Rails can get quite complex, because sometimes the page you are trying to link to might not even exist

(e.g, I want a link here to the 18th blog post if there is an 18th blog post)

You can’t do something like that with basic HTML, so the Rails guys and gals created a Link helper for us. We pass some instructions into the link helper and it automatically generates the correct link to our desired destination for us. It’s pretty brilliant.

Let’s go ahead and replace the <a> tags in our last example with the link helper.

So we want to use the link_to helper to link the string “About” to the Pages controller and the About action inside that controller. Here’s how the link will look, using the link_to helper.

Rails is going to replace this with a link with the anchor text “About” and the correct path to the pages controller and the about action. It works like magic but it’s really not, it’s the code in the link_to helper that makes this happen.

Now go ahead and use this format to link “Contact” to the contact action in the pages controller.

You can look at the Rails Documentation (google “link_to helper” for more information on how to use this helper.

Your view template should now look like this

I added a div around both groups of links, so we can easily differentiate them in the browser.

Now let’s go ahead and view our work in the browser:

You’ll see that we have two sets of links. Now if we inspect element so we can peep the code behind this page in the browser

you’ll see that the link we created ourselves and the one generated by Rails are exactly the same. Rails used the link_to helper to automatically generate a link with the correct path for us, so we didn’t have to worry about figuring out the correct path to each action.

One more thing before we move forward

We didn’t need to specify controller: :pages, because the about action we are trying to link to is in the pages controller (where we are right now). You only need to specify the controller when you are linking to an action that resides in another controller.

So if we take that out and save

the links will still work as expected and as you can see in the browser below, there is no change to the link and url structure.

Named Routes

Now before we move on and talk about the Image helper, let me show you an even easier way to specify the links destination. It’s called named routes. By naming your routes, you no longer have to secify the controller or the action. Just call it’s name and rails will link you to it.

You name your routes in the routes.rb file like so:

at the end of lines 2 and three as you can see, all we had to do was add a comma and us the as: option to name the route with a symbol (:about and :contact in this case).

For those not familiar with Ruby, as: is the new way of writing the hash rocket. This is what it looked like before “:as =>”. (This was an unnecessary side note right?).

Now if we go back to the about template:

We can take all that purple stuff out and just tell rails to link us to the about_path and contact_path respectively. Like this:

and the links should work exactly the same. We have named the routes correctly in the routes.rb file, so now calling that name will tell Rails exactly how it needs to route that file.

Image Helpers

Now let’s get back to helpers. The image helper help us add images to our view templates pretty easily.

Google “cat images” and just save any one of them to your desktop as “cat”. Cats are so cute.

Repeat that search with “dog images” and save any one of them as “dog” and copy those two images from your desktop, into the images folder (app> assets > images) of your application.

So now we have a cat and a dog in our images folder. Cool.

We are going to use the image helper to add the cat image to our view template (inline).

In your about.html.erb view template, create a <div> and open up an erb tag. Inside this erb tag, we use the image helper (image_tag) followed by the name of the image file as a string (i.e. in quotes).

You can also pass in a few other options like size, alternative text, etc. From the rails documentation:

Now let’s head back to the browser. Look at that. So cute!

The other thing you might want to with images in Rails, is to display them as a background image.

Let’s open another <div> with a class “dog_image”.

Now let us head over to pages.scss (app > assets > stylesheets > pages.scss). Rails generated this file for us when we generated our pages controller.

first, let us empty its contents (remove lines 1–3) and then rename the file to (pages.css), so it doesn’t use the scss preprocessor. If you don’t know what scss is, don’t worry it’s just a faster way of writing css which won’t be covered in this course.

Now let’s fill in the CSS. We’ll add a width and height just so our image can show on the page (because the div is empty) and then we’ll just use the background-image declaration like in normal CSS.

What’s special here is that you only have to type the name of the image in quotes and rails will find it. There is no need to specify its path:

And that’s it. Now let’s head over to the browser to see what we’ve got.

Cool.

--

--

Felix
The Blog of Felix Oginni

In the next article, I discuss how to use your typography system to define clear hierarchy in Product & Marketing design. Join my newsletter to get notified.