<— TutorialStepOne | Tutorial | TutorialStepTwo —>
How to setup your DB using only migrations—the cool way.
Go to TutorialStepTwo and setup your database.yml file appropriately (I know it jumps steps, but hey, no harm done).
go to your “root” directory of your new rails project.
Run ruby script/generate migration firstHack. Edit the file db/migrate/001_first_hack.rb to read
class FirstHack < ActiveRecord::Migration
def self.up
create_table :people do |table|
# note that "id" is added implicitly, by default
table.column :name, :string
table.column :street1, :string
table.column :street2, :string
table.column :city, :string
table.column :state, :string
table.column :zip, :string
end
end
def self.down
drop_table :people
end
end
Rails-2.0 provides a new alternative format for declaring migrations in a slightly more efficient format. See bellow.
Also, the migration tool now create the migration script for the model. You don’t have to run ruby script/generate migration firstHack.
Directly run:
ruby script/generate model Person
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/person.rb
create test/unit/person_test.rb
create test/fixtures/people.yml
create db/migrate
create db/migrate/001_create_people.rb
and edit db/migrate/001_create_people.rb
create_table :people do |t|
t.string :name
t.string :street1
t.string :street2
t.string :city
t.string :state
t.string :zip
t.timestamps
end
and run:
rake db:migrate
Done !
New migration format:
table.column :name, :string
becomes (.column disapear and is replaced by the type of the column, here string)
table.string :name
so the create_table loop becomes:
create_table :people do |table|
# note that "id" is added implicitly, by default
table.string :name
table.string :street1
table.string :street2
table.string :city
table.string :state
table.string :zip
end
See Also: rails-2.0 sexy migration screencast, rake-2.0 release notes
then run rake db:migrate and voila! The table appears. Now we wish to create an entry for superman. To do this let’s create an ActiveRecord entry and save it. Unfortunately this requires us to create a ‘model’ of People first.
run ruby script\generate model Person it creates a “model” which describes person to ActiveRecord, so we can use it.
Now let’s create superman in the Console ruby script/console and enter
superMan = Person.new
superMan.name = "Superman"
superMan.street1 = "123 Somwhere"
superMan.street2 = ""
superMan.city = "Smallville"
superMan.state = "KS"
superMan.zip = "123456"
superMan.save
<— TutorialStepOne | Tutorial | TutorialStepThree | or jump directly to TutorialStepFour (Creating a model, already done here) —>