Imagine you have to write new migration with a lot of code and this migration should have a lot of code, code which you have already wrote in older migration and this required code is exactly up/down/change part of those migration. Another words you would like to run migration part (up, down or change) in the new migration. Pay attention - you have to write or copy paste a lot of code You have 2 variants how to overcome this issue:
The simplest and boring solution - it is copy and paste this code, or write it with scratch. This is not our case. Old code and new code will mix and you will have a huge amount of disgusting code - you won’t able to detect which is new code and which is old
Use oldest migration in DRY way. Just use those code as you use another class, for instance User model which you probably have
In one project I had to rollback my old migration which has a lot of code. Check out this code:
As I have already said I would like to rollback it in my new migration on up.
Write new migration and paste there this code is not right solution. I think you are agreed with me.
I think the best solution will be to include this migration in my new migration then use this migration class as usual code (yes - migration is a class too and we are able to do it). So the final code below:
See the first line (1): require File.join(Rails.root, 'db/migrate/20121107173946_add_search_content_to_products.rb'). With this line I include migration file and after this we are able to use old migration’s class. On the fifth line (2) we I just use it: AddSearchContentToProducts.new.down to rollback old migration. On down I have to up this migration, see mark (3): AddSearchContentToProducts.new.up.
In this example I had to rewrite stored procedure for postgresql database and I’ve got clean and DRY solution as you can see. Imagine how many code I would have if I just pasted all entire migration in the new! I hope you will find this article useful and if you have issues like I had you won’t have problems now to solve them.
UPDATE 26.06.2013: In Rails 4 new method is appeared which allows to revert all migrations. Check it out: