The Duke's Discoverage |
Timo is the founder & CEO of Dealmachine. He lives in Helsinki, Finland and when he's not working on startups, he enjoys deejaying and photography. |
When we first start learning new languages, we try to remember phrases to work with, such as “Qu’est-ce que c’est?” (French), and then break them into pieces while trying to understand why they work like they do. Same goes with learning Ruby & Rails: to get started, we need some basics we can start tweaking bit-by-bit. Here’s a set of those recipes.
Before starting, you need to have Rails 3.1 installed on your computer
..or whatever is the most recent version. That’s a bit tricky and differs on each platform, so I won’t go into that here. The folks at RailsGirls did a great job in assembling installation instructions for each of the most common platforms: http://railsgirls.com/install.html
Creating your first Rails project; the command line interface (CLI)
The next oddness for newbies is the fact that you have to use the command line interface (also known as Terminal in OS X and Command prompt in Windows) a lot – and you thought that text-based UI’s were a thing of the past..
Here’s some resources to better understand how the CLI works:
So, fire up that command line and navigate to a folder you’re comfortable creating a folder in (usually, it could be something like /home/Myusername/Documents/). If you don’t know where you are, try the
pwd -command (print working directory; in the Windows CLI you could use echo %cd% or just cd), which will print out the directory you are in.
To list the contents of a directory, just type ls or in Windows dir.
To move between directories, use the cd command. You mostly use it with some parameters, such as “cd subfolder” (when you want to go into a folder called subfolder or “cd ..” if you want to back down to a parent directory.
Use the mkdir command to create a directory. For instance, if you want to create a directory called “Rails”, you would type “mkdir Rails”. If you were in the folder “/home/Myusername/Documents”, the created folder would exist in “/home/Myusername/Documents/Rails”.
Creating the Rails project

Figure 1: Runnin “bundle install”
Once you have Rails along with all the required dependencies installed, you can verify this by typing “rails —version”. The CLI should respond with something like “Rails 3.1.1” If not, please consult the RailsGirls installation guide above!
So, let’s imagine you’ve created a folder in /home/Myusername/Documents/Rails, and you want to create a new Rails application.
Start with rails new myapplicationname. Notice, that you should not have any whitespace (” “) in your application name, otherwise you will end up with some unexpected results. So if I were to create an application for listing skateboarding spots around the world, I’d go with something like rails new spots. The shorter and descriptive, the better (in my opinion).
Now you should be presented with something like Figure 1 and after the bundle install has finished, something like Figure 2.

Figure 2: Rails project successfully created
If you get something else than “Your bundle is complete!”, you have a problem in your Rails installation and should again consult the installation instructions above.
Testing the Rails development server
Before we get to actually creating stuff, let’s see if we get our Rails server running.
Type
rails server or the shorthand rails s in your project folder, and you should get something like:

Figure 3: The Rails server accepting requests in port 3000
What you should understand from this is that now you have a lightweight WEBrick development server running in the CLI window and accepting requests at port 3000. Now, when you go to port 3000 on your local computer (or localhost), you should see something like this:

Figure 4: A successful Rails setup running at http://localhost:3000
Another thing you should understand is that when the WEBrick server is running in your CLI window, you cannot do anything else with that particular window. You need to create a new CLI window or tab in order to continue working. Also, when you do create a new tab or window, it will most probably default the working directory into something else, and then you’ll need to use the ls, dir, pwd and/or cd commands, depending on your system and the directory you are in.
To close the server down, use the key combination of Control + C.
Creating your first scaffold
A technique known as scaffolding, in the context of Rails projects, means that Rails creates a set of filed for you that you can start tweaking. Later, when you become a better programmer, you most probably don’t need the scaffolding anymore. However, as learning through tweaking code is easier than trying to create everything from scratch, scaffolding is probably the most convenient way of getting started with Rails.
It will give you the tools to maintain (create, read, update, destroy) a list of a certain type of resource of your liking, such as restaurants, dogs, cats, or whatever. Check out the example below to get a concrete understanding of what the resource can be.
Among other things, the command rails generate scaffold Modelname attribute:type creates a Model with a controller and a set of view files (index, show, edit. Example: you want to create a resource named “City”, which means you want to maintain of a list of cities.
Then you would use the generate scaffold command like this:

Figure 5: rails generate scaffold City name:string population:integer founded:date
Which means you are going to list cities and keep track of their names, populations and date founded. In order to get this running, you still need to migrate the database. This means updating the database according to a migration the scaffold created for you. The function of the migration is to keep the structure of the database and the data in it sync with the code you are creating. Also it provides you with the means of rolling back the changes you just made if you find out that they were not what you actually wanted.
The migration is done with the command bundle exec rake db:migrate

Figure 6: bundle exec rake db:migrate
Now, give you still have your WEBrick server running in another tab or window, when you point your browser to http://localhost:3000/myresourcenameinplural , for instance http://localhost:3000/cities, you should see something like this:

Figure 7: Listing cities
Yay! Now you have your first Rails application going.
Understanding how Rails works: The MVC architecture
Before reading further, check out the awesome Bentobox model by Linda Liukas (RailsGirls), which clarifies all these different terms and opens up the top-level architecture or technology stacks of any web application (also contains concrete examples of apps like Etsy or Foursquare!)x
Rails is built on a design patter called Model-View-Controller (or MVC). There are alternative design patterns as well, but MVC seems to be one of the most popular ones out there.
What the MVC means is that the application is split into three main parts: the model handles communication with the database (which is actually a separate part of, as you can see from the Bentobox model), the controller handles incoming HTTP requests from users’ browsers or other computer systems, as well as showing the right view for each request. Finally, the views are templates, where the dynamic data from the model (as instructed by the controller) is inserted, after all kinds of calculations and other logic.
In other words “Models do the grunt work, views are the happy face, and controllers are the masterminds behind it all.” -Betterexplained.com
The reason to use the MVC pattern is to keep things nice and tidy, so that everyone developing the app knows where to find each kind of code. What you need to understand from this is that you should not do heavy calculations in the views or controllers, but in the models. The controllers are used to prepare the data for different uses. The views should be “dumb” and just present data given to them by the controller.
Start to modify your application
The easiest way to start developing your application is studying the HTML/ERB files found in the views directory. (myprojectname/app/views/modelname/).

Figure 8: the views folder with index.html.erb
In Figure 8 you see the contents of the views/cities/ folder. Inside, you’ll see different files with descriptive names. These filenames are in sync with the cities controller and eventually the City model, so you cannot start changing the names without breaking stuff. Let’s study the contents of index.html.erb inside the cities view folder instead!

Figure 9: Cities index.html.erb file with the dynamic listing highlighted
Above, in Figure 9, you see the contents of the index.html.erb created by the scaffold command we used earlier.
Some of the file is pure HTML, some of it is ERB (or Embedded RuBy). The ERB parts are signified by either <% ruby code here %> or <%= ruby code printing out something here%>. HTML is just <start tag here> or <single tag here /> or </end tag here>.
The idea is that you can dynamically create HTML by using the ERB templating engine. As a result, you can say things like <%= city.name %>, which will print the name of each record of cities in the database.
You could start by editing the non-dynamic parts of the HTML.ERB page, for instance changing the heading of the page (<h1>Heading here</h1>).
Where from here?
Now that you have created your first scaffold, try to tweak the HTML, and if you’re in the mood for it, futher explore the possibilities of using the dynamic ERB templating engine, for instance by playing around with Ruby’s string methods, such as <%= city.name.reverse %>, which will print the name field out in reverse. Great for finding out palindromes!
More resources for autonomous learning
If you want to proceed on your own, good starting points are, for instance (please suggest more in the comments!):
*The official Ruby on Rails API
*Why’s Poignant Guide to Ruby
*RailsCasts
*Nodeta’s rich front-end to the Rails API, APIdock
*Learn Ruby the Hard Way
*Codeacademy
*TryRuby
*The Pragmatic Programmers’ Rails book, available as an PDF eBook
In the next episode..
Next, we’ll go into actually programming some logic. Thanks for reading!