Rails Migrations for Dummies, and Jeff
On a mailing list I belong to (<nerd/>), Jeff wrote:
How hard was it to get going with Migrations?
Very easy. Instead of creating your table or column or whatever through traditional means, do this:
- Run script/generate migration products_table. The script tells you it creates a file called db/migrate/1_products_table.rb.
- Edit the file. Initially it looks like this:
Change it so it looks like this:class ProductsTable < ActiveRecord::Migration def self.up end def self.down end end
Full docs at http://ar.rubyonrails.com/classes/ActiveRecord/Migration.html.class ProductsTable < ActiveRecord::Migration def self.up create_table :products do |t| #id column is add automatically when you use create_table t.column :name, :string t.column :price, :integer #anybody who chooses :float deserves what they get t.column :date_added, :date end end def self.down drop_table :products end end
- Run rake migrate. This opens up your DB and looks for a table called schema_info. If not found, it creates the table. If found, it pulls the single row from the table containing the database "version number." It then runs all the available migrations (in the db/migrate directory) with a number greater than the DB version number, in numerical order, and finally sets the new DB ver # in the schema_info table.
That's all!
- Obviously, there's a way to do rollback, else we wouldn't have wasted the time to write the down method. From the looks of the Rakefile, it's VERSION=0 rake migrate.
- I'm not sure what happens if Alice generates 5_quantity_remaining.rb and commits, and Bob generates 5_system_settings.rb and commits without noticing and renaming his to 6_.... The simple answer is "read your svn up log" anyway.
0 Comments:
Post a Comment
<< Home