Use Ruby on Rails to Maintain Database Schema
For my J2EE-based RSS reader project, I have managed to successfully use Rails to maintain my database schema.
Quick summary:
* Create a Rails project.
* Create a new model.
* Use rake db:migrate to upgrade or to downgrade the database schema.
Detailed steps:
* Go to your Rails development directory (mine is ~/Projects/rails).
* Create a new Rails project:
rails my_project_name
* Enter the directory:
cd my_project_name
* Modify the config/database.yml using your favorite text editor (I like vi).
* I just use the development mode.
* Modify it to fit your need:
development:
adapter: mysql
database: your_database_name
username: your_user_name
password: your_password
host: your_host_name
port: 3306 #MySQL usually uses 3306
* To create a users table, type the following:
ruby script/generate model users
* You should get the following output:
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/users.rb
create test/unit/users_test.rb
create test/fixtures/users.yml
create db/migrate
create db/migrate/001_create_users.rb
* The last output, db/migrate/001_create_users.rb, is what you’re looking for.
* Using your favorite text editor, edit the db/migrate/001_create_users.rb file.
* Here is the content of my db/migrate/001_create_users.rb file:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :first_name, :string
t.column :last_name, :string
t.column :user_name, :string
t.column :password, :string
end
end
def self.down
drop_table :users
end
end
* Finally type:
rake db:migrate
If your setup is correctly done, you should have the users table.
In the next part, I will dive further into schema versioning.
January 20th, 2008 at 5:19 am
Sweet use of migrations for a non-Rails project.
Migrations are such a clean way to be able to roll database schemas forward and backward, as well as to be able to tie database schema versions with code versions in the code repository.
Projects that don’t do this will often have the problem where they can restore a past version of the code, but not have any idea what the corresponding database schema was.
January 20th, 2008 at 1:15 pm
Thank you.
I agree with your comments.
I would like to add that using Rails to maintain database schema helps the developers to eliminate that “one more thing” to do.