Database Tables, Controllers for Ruby-on-Rails Applications
In this third part of a four-part article series on building a basic Ruby-on-Rails application, you will learn how to create a database table, generate a controller, and more. This article is excerpted from chapter three of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Database Tables, Controllers for Ruby-on-Rails Applications (Page 1 of 2 )
Creating a Database Table
We need to create a table in the database. We could do this with a database administration tool, or even manually using SQL, but Rails provides a much more efficient facility for table creation and maintenance called migrations. Itís called a migration because it allows you to evolve, or migrate, your schema over time. (If youíre not familiar with databases, tables, and SQL, consult Appendix B for the basics.)
Schema is the term given to the properties that make up a table: the tableís name, its columns, and column types, as well as any default values a column is to have. And whatís the best part about migrations? You get to define your schema in pure Ruby. This is all part of the Rails philosophy that you should stick to one language when developing. It helps eliminate context switching and results in higher productivity.
As you can see from the output of the model generator, it created a new file indb/migratecalled001_create_events.rb. Notice that migrations are named with a numeric prefix, starting at 001. Since migrations are run sequentially, this number represents their position in the queue.
Letís open this file and take a peek. Itís shown in Listing 3-2.
class CreateEvents < ActiveRecord::Migration def self.up create_table :events do |t| end end
def self.down drop_table :events end end
In its initial, generated form, the migration is a blank canvas. But before we go any further, letís note a few important items. First, notice the class methods:upanddown. For each migration, you define instructions for updating in theupmethod, and use thedownmethod to roll back any changes. So, if you were to, say, create a new table in theupmethod, you would drop the table in thedownmethod, thereby reversing your changes. In fact, thatís exactly what the generator did for us already: Theeventstable gets created onupand dropped ondown. Pretty slick, isnít it?
Note You can easily spot the difference between class and instance method definitions in a Ruby class by looking for theself prefix. For more about Ruby classes, see Appendix A.
Weíve gone ahead and filled out the details for you. Without having seen a migration before, you should be able to tell exactly whatís going on by looking at Listing 3-3.
class CreateEvents < ActiveRecord::Migration def self.up create_table :events do |t| t.column :title, :string t.column :location, :string t.column :occurs_on, :date end end
def self.down drop_table :events end end
Letís step through the code. First, we use thecreate_tablemethod, giving it the name of the table we want to create. Inside the code block, we use thecolumnmethod to create columns in the table. Thecolumnmethod takes the name of the column and its type. (For a full description of the available field types you can create in your migrations, seehttp://api.rubyonrails.org/classes/ActiveRecord/ Migration.html.)
On its own, this migration does nothing. Really, itís just a plain-old Ruby class. If we want it to do some work and create a table in the database for us, we need to run it. To run a migration, you use the built-in Rake task that Rails provides calleddb:migrate.
Note Rake is a build language for Ruby. Rails uses Rake to automate several tasks, such as running database migrations, running tests, and updating Rails support files. You can think of Rake tasks as little utility programs. For a list of all available Rake tasks, runrake -Tfrom your Rails project directory. For more information about Rake, including complete documentation, seehttp://rake.rubyforge.org/.
From the command line, type the following to run the migration and create theeventstable. Youíll recognize this command as the same one we used to test the database connection. We sort of hijacked it for our test, knowing that it will attempt to connect to the database and thus prove whether the connection works. Since there were no existing migrations when we first ran it, it didnít do anything. Now that we have our first migration, running, it will result in a table being created.
Just as the output says, the migration created a new table. If you were to try to run the migration again (go ahead, try it!), you would see that nothing happens. Thatís because Rails keeps track of the current migration version and it knows that youíre at version 1, so thereís nothing left to do.