In a recent series of articles, you learned how to set up a proof of concept for an online bookstore created using Ruby-on-Rails. In this four-part article series, you'll start creating the application for real, using test-driven development. This article is excerpted from chapter two of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Author Management for an Online Bookstore - Creating the ActiveRecord Model (Page 3 of 4 )
ActiveRecord is the object-relational mapping system in Rails, thus denoting the Model in the Model-View-Controller (MVC) pattern. The job of the model part in the MVC paradigm is to take care of handling the data storage of the application. However, ActiveRecord is much more than simply a Ruby library for creating and executing SQL queries. It automatically maps database tables to classes in a Rails application, creates public methods for all database fields, and adds a load of useful methods for accessing the data in the database.
As noted earlier, we will be completing sprint 0 of our project in this chapter. This sprint involves five stories related to managing authors in the Emporium application. So first, we need a way to store our authors.
Using ActiveRecord Migrations
We could create the authorstable by using the direct SQL commands. However, Rails has a great database-agnostic system for keeping up with the changes in the database—migrations.
When using migrations, the description of the database is written in pure Ruby. The different database adapters in Rails then interpret these commands to database-specific SQL commands. Another big advantage of using migrations is that you can keep track of the changes in the database schema and traverse back and forth between different schema versions. You can also deploy the migrations to multiple database servers simultaneously—something that will be very valuable when your server stack gets bigger.
Creating the Schema
Because our database doesn’t contain anything yet, we start by creating the initial schema. As of Rails 1.1, creating a new ActiveRecord model will also create a new migration file for the corresponding table, so we use thescript/generatecommand to create both theAuthorclass file and the database migration for theauthors table:
Not only did this single command create a model class file for theAuthormodel, but it also created a skeleton for unit tests for that class and a new migration file,001_create_authors.rb. The number001at the beginning of the filename means that we’re talking about the first migration for this application.