views:

443

answers:

2

I have 4 related migrations in my Rails app:

First 3 migrations create one table each in the self.up and and drops them in their respective self.down methods.

4th migration runs a rake task that loads data to all three (in self.up). I am thinking what to put in self.down of this migration to delete the rows from the 3 tables?

Am I doing it wrong? Probably should have created one migration where I create 3 tables and load the data in self.up and just drop all three tables in the self.down method?

+3  A: 

There isn't really a right or wrong way to do this. Based on what you've done, the 4th migration should just unload the data in its down method. Each down should only undo the actions of the up.

Loading data in the migration that creates the table is certainly not required. If you have 3 tables that create has_many or belongs_to relationships then it would make sense to put the data in a separate migration so you can create the relationships and then use them in your data load.

All that aside, if you have a rake task to load data, why bother with a migration that runs that rake task? Just make running the rake task part of your install, or just use your rake task to load or unload some demonstration data.

Generally I keep my migrations schema focused, and I'd put any data loading in a rake task I call independently.

danivovich
__All that aside, if you have a rake task to load data, why bother with a migration that runs that rake task? Just make running the rake task part of your install, or just use your rake task to load or unload some demonstration data.__ => mainly to make life easier for other developers in the team. So they don't have to remember one more step of running a rake task.Thanks for the direction though. I kept thinking, they should go together. Now I can just delete the rows in the 4th migration in self.down.
vulcan_hacker
+3  A: 

This is wrong!

Migrations should be used only for migrating your Data Model not your Data.

Rails 2.3.4 adds 'seeds'. This is a file in db/seeds.rb contains ruby code to 'bootstrap' your database. This is a great way to create semi-static content for your database like categories, look-up tables or user accounts.

You can then load the seed data with a simple rake task

rake db:seed
Ariejan
Yes I agree and thanks for the answer. I was working with rails 2.2.2 back then. I heard about db:seed recently and using it in my project. Loading data with migrations never seemed right to me.
vulcan_hacker