Okke's blog

Tuesday, January 17, 2006

ActiveRecord::Schema - use it!

ActiveRecord::Schema is a way to create your database schema without having to resort to SQL! But how and when to use it, that might be a little confusing. So, here goes. (This is more-or-less an adapted version of DHH's excellent screencast. But it's always nice to be able to read things back. Okay, let's start with the beginning. There is a database already, but you don't want to edit it with normal SQL anymore. The first step is to create the ruby definition file of the database. rake db_schema_dump Now you'll have a file called schema.rb in your /db/ directory. This file shouldn't be edited really; it's for importing purposes only. So, if you want to deploy your current database somewhere else, or on another database that supports migrations, you can use this file to create the tables again: rake db_schema_import Notice that the methods used in the schema.rb file are all to be found at ActiveRecord::Migrations In the screencast is David, as he puts it himself, 'running with scissors'. Instead of creating a migration (I'll explain migrations later), he edits the field manually. Although this can be done with an empty database, it isn't possible when using a database with tables already defined. You'll first have to destroy all tables, and then import them again. But hey, then you'll lose all your data. What to do? Here's where migrations come in. If you want to make a change to the database, for example, add a new column to the database, let rails first create a migration file for you: ./script/generate migration MigrationName There will be a migration generated in the /db/migrate/ folder. Because it'll probably be your first migration, it's named 001_migration_name.rb. In this migration file, there are 2 methods defined: self.up and self.down. In self.up, add all things that have to be done to update the rows, and that includes filling them with data. self.down does things the other way around: it is called when the migration has to be reversed. self.down should raise an IrreversibleMigration error when, for example, data is deleted that can't be brought back. If you don't ever want to be bothered with the SQL for creating and editting tables, you should also edit your environtment.rb file in the /config/ directory. Uncomment the following line: config.active_record.schema_format = :ruby If there are any uncertainties, I would love to help you out. Well, that's it for my multi-shurking today. I always find things to postpone my developing works... Either trying out different editors, finding little small bugs or improvements and writing bug reports for them, typing entries for my blog... Just as long as I don't have to either do uni or developing work... *sigh*


Post a Comment

Links to this post:

Create a Link

<< Home