The Database Renaissance: Managing Schema with Rails ActiveRecord Migrations
If you're still manually emailing SQL dump files to your teammates in 2005, you're living in the dark ages. Web development is finally getting the tools it deserves. With the release of Ruby on Rails 1.0 on the horizon, we're seeing the death of 'Big Design Up Front' and the birth of truly agile database management.
The star of the show is ActiveRecord Migrations. We no longer think in terms of SQL scripts; we think in terms of Ruby classes that evolve our schema over time.
Why Migrations?
In a traditional J2EE or PHP project, keeping your development and production databases in sync is a nightmare. Migrations solve this by providing a domain-specific language (DSL) to describe changes.
Each migration is a Ruby file with a timestamp (or a sequence number). It contains two methods: self.up (how to apply the change) and self.down (how to undo it).
class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.column :name, :string
t.column :description, :text
t.column :price, :decimal, precision: 8, scale: 2
t.column :created_at, :datetime
end
end
def self.down
drop_table :products
end
end
The Power of rake db:migrate
Executing your schema changes is now a single command: rake db:migrate. Rails tracks which migrations have already run by looking at a special schema_info table in your database.
If you make a mistake, you don't have to manually un-fudge your SQL. Just run rake db:rollback (or migrate to a specific version) and Rails will execute the self.down blocks for you.
Adding Columns on the Fly
Need a new feature? Just generate a new migration.
class AddStockToProducts < ActiveRecord::Migration
def self.up
add_column :products, :stock, :integer, default: 0
end
def self.down
remove_column :products, :stock
end
end
Database Agnosticism: The 'Rails Way'
The beauty of ActiveRecord is that the Ruby code above looks the same whether you're using MySQL 4.1, PostgreSQL, or SQLite. Rails handles the translation to the specific SQL dialect. This is the hallmark of the 'Convention over Configuration' philosophy. We're not just writing code; we're building an application that isn't tied to the implementation details of the underlying storage.
Your schema.rb file becomes the single source of truth for your database structure. It should be checked into your version control (CVS or the new Subversion) alongside your application code.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development