Completing the Database

The migration we created previously in this chapter built just one of the tables in our database. Referring back to the data structure we designed in Chapter 2, there are two more database tables to add: companies and addresses. The next two sections give a brief overview of how to create these using migrations. In both cases, the migrations are simple and don't require any commands we haven't already encountered.

The companies Table

Create the model and migration for the companies table from the command line with:

$ ruby script/generate model Company

Edit db/migrate/002_create_companies.rb and insert this code:

class CreateCompanies < ActiveRecord::Migration
def self.up
create_table :companies do |t|
t.column :name, :string, :null => false
t.column :telephone, :string, :limit => 50
t.column :fax, :string, :limit => 50
t.column :website, :string
t.column :address_id, :integer
t.column :created_at, :timestamp
t.column :updated_at, :timestamp
end
end
def self.down
drop_table :companies
end
end

The addresses Table

Create the model and migration for the addresses table from the command line with:

$ ruby script/generate model Address

Edit db/migrate/003_create_addresses.rb and insert this code:

class CreateAddresses < ActiveRecord::Migration
def self.up
create_table :addresses do |t|
t.column :street_1, :string, :null => false
t.column :street_2, :string
t.column :street_3, :string
t.column :city, :string
t.column :county, :string
t.column :post_code, :string, :limit => 10, :null => false
t.column :created_at, :timestamp
t.column :updated_at, :timestamp
end
end
def self.down
drop_table :addresses
end
end

Generating the Remaining Tables

Applying the migrations to the database is done via the command line with:

$ rake db:migrate
(in /home/demo/workspace/Intranet)
== CreateCompanies: migrating ======================================
-- create_table(:companies)
-> 0.5015s
== CreateCompanies: migrated (0.5022s) =============================
== CreateAddresses: migrating ======================================
-- create_table(:addresses)
-> 0.2078s
== CreateAddresses: migrated (0.2089s) =============================

Note that this creates both of the tables: Rails recognizes that our database is at version 1, meaning there are migrations for versions 2 and 3 to be applied.

You can use your MySQL client to check the generated tables. If you've made a mistake, you can roll back to a previous version of the database using:

$ rake db:migrate VERSION=1

(Replace "1" with the migration number you want to roll back to—see the section Rolling Back to a Previous Version of the Database for more details.)

With our database completed, we are now ready to look at fleshing out the basic models, adding validation and table-to-table relationships.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.152.198