Article
Rails For Beginners: All You Need To Know!
The Model-View-Controller Architecture
The model-view-controller (MVC) architecture that we first encountered in Chapter 1 is not unique to Rails. In fact, it predates both Rails and the Ruby language by many years. However, Rails really takes the idea of separating an application's data, user interface, and control logic to a whole new level.
Let's take a look at the concepts behind building an application using the MVC architecture. Once we have the theory in place, we'll see how it translates to our Rails code.
MVC in Theory
MVC is a pattern for the architecture of a software application. It separates an application into the following three components:
- models: for handling data and business logic
- controllers for handling the user interface and application logic
- views for handling graphical user interface objects and presentation logic
This separation results in user requests being processed as follows:
- The browser, on the client, sends a request for a page to the controller on the server.
- The controller retrieves the data it needs from the model in order to respond to the request.
- The controller hands the retrieved data to the view.
- The view is rendered and sent back to the client for the browser to display.
This process is illustrated in Figure 2.
![]()
Separating a software application into these three distinct components is a good idea for a number of reasons, including the following:
It improves scalability (the ability for an application to grow).
For example, if your application begins experiencing performance issues because database access is slow, you can upgrade the hardware running the database without other components being affected.
It makes maintenance easier.
As the components have a low dependency on each other, making changes to one (to fix bugs or change functionality) does not affect another.
It promotes reuse.
A model may be reused by multiple views, and vice versa.
If you haven't quite got your head around the concept of MVC yet, don't worry. For now, the important thing is to remember that your Rails application is separated into three distinct components. Jump back to Figure 2 if you need to refer to it later on.
MVC the Rails Way
Rails promotes the concept that models, views, and controllers should be kept quite separate by storing the code for each of these elements as separate files in separate directories.
This is where the Rails directory structure that we created back in Chapter 2 comes into play. The time has come for us to poke around a bit within that structure. If you take a look inside the app directory, which is depicted in Figure 3, you'll see some folders whose names might be starting to sound familiar.

As you can see, each component of the model-view-controller architecture has its place within the app subdirectory -- the models, views, and controllers subdirectories, respectively. (We'll talk about that helpers directory in Chapter 6.)
This separation continues within the code that comprises the framework itself. The classes that form the core functionality of Rails reside within the following modules:
ActiveRecord
ActiveRecord is the module for handling business logic and database communication. It plays the role of model in our MVC architecture.
(While it might seem odd that ActiveRecord doesn't have the word "model" in its name, there is a reason for this: Active Record is also the name of a famous design pattern -- one that this component implements in order to perform its role in the MVC world. Besides, if it had been called ActionModel then it would have sounded more like an overpaid Hollywood star than a software component ...)
ActionController is the component that handles browser requests and facilitates communication between the model and the view. Your controllers will inherit from this class. It forms part of the ActionPack library, a collection of Rails components that we'll explore in depth in Chapter 5.
ActionView
ActionView is the component that handles the presentation of pages returned to the client. Views inherit from this class, which is also part of the ActionPack library.
Let's take a closer look at each of these components in turn.
ActiveRecord (the Model)
ActiveRecord is designed to handle all of an application's tasks that relate to the database, including:
- establishing a connection to the database server
- retrieving data from a table
- storing new data in the database
ActiveRecord also has a few other neat tricks up its sleeve. Let's look at some of them now.
Database Abstraction
ActiveRecord ships with database adapters to connect to SQLite, MySQL, and PostgreSQL. A large number of adapters are also available for other popular database server packages, such as Oracle, DB2, and Microsoft SQL Server, via the RubyGems system.
The ActiveRecord module is based on the concept of database abstraction. As we mentioned in Chapter 1, database abstraction is a way of coding an application so that it isn't dependent upon any one database. Code that's specific to a particular database server is hidden safely in ActiveRecord, and invoked as needed. The result is that a Rails application is not bound to any specific database server software. Should you need to change the underlying database server at a later time, no changes to your application code should be required.
Examples of code that differs greatly between vendors, and which ActiveRecord abstracts, include:
- the process of logging into the database server
- date calculations
- handling of boolean (
true/false) data - evolution of your database structure
Before I can show you the magic of ActiveRecord in action, though, we need to do a little housekeeping.
Database Tables
Tables are the containers within a database that store our data in a structured manner, and they're made up of rows and columns. The rows map to individual objects, and the columns map to the attributes of those objects. The collection of all the tables in a database, and the relationships between those tables, is called the database schema.
An example of a table is shown in Figure 4.
![]()
In Rails, the naming of Ruby classes and database tables follows an intuitive pattern: if we have a table called stories which consists of five rows, this table will store the data for five Story objects. The nicest thing about the mapping between classes and tables is that you don't need to write code to achieve it -- the mapping just happens, because ActiveRecord infers the name of the table from the name of the class.
Note that the name of our class in Ruby is a singular noun (Story), but the name of the table is plural (stories). This relationship makes sense if you think about it: when we refer to a Story object in Ruby, we're dealing with a single story. But the SQL table holds a multitude of stories, so its name should be plural. While you can override these conventions -- as is sometimes necessary when dealing with legacy databases -- it's much easier to adhere to them.
The close relationship between tables and objects extends even further: if our stories table were to have a link column, as our example in Figure 4 does, the data in this column would automatically be mapped to the link attribute in a Story object. And adding a new column to a table would cause an attribute of the same name to become available in all of that table's corresponding objects.
So, let's create some tables to hold the stories we create.
For the time being, we'll create a table using the old-fashioned approach of entering SQL into the SQLite console. You could type out the following SQL commands, although typing out SQL isn't much fun. Instead, I encourage you to download the following script from the code archive, and copy and paste it straight into your SQLite console that you invoked via the following command in the application directory:
$ sqlite3 db/development.sqlite3
Once your SQLite console is up, paste in the following:
Example 4.2. 02-create-stories-table.sql
CREATE TABLE stories (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"name" varchar(255) DEFAULT NULL,
"link" varchar(255) DEFAULT NULL,
"created_at" datetime DEFAULT NULL,
"updated_at" datetime DEFAULT NULL
);
You needn't worry about remembering these SQL commands to use in your own projects; instead, take heart in knowing that in Chapter 5 we'll look at migrations. Migrations are special Ruby classes that we can write to create database tables for our application without using any SQL at all.