RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

What is the Rails Way to perform a data update after a structural db change via db:migrate?

I'm changing a relationship in my database from has_many to a has_many :through. So right now I have:

class Brand < Ar::Base
  has_many :products
end

class Product < AR::Base
  belongs_to :brand
end

and I'm going to add a join table.

But of course I need to update the database with data after that. I have seen that it is not good practice to do this in the confines of the migration. Where is the best place to perform this, knowing that I have to then run another migration after the data update is complete (i.e. removing the original brand_id column from the products table)?

Upvotes: 0

Views: 316

Answers (3)

aceofspades
aceofspades

Reputation: 7586

One-time changes like this can be done with ruby code in the migration. Migrations aren't just for schema changes. The idea is that migrations, by there version/datecode, are ensured to only be run once.

Upvotes: 2

johnmcaliley
johnmcaliley

Reputation: 11055

I think you should at least include the call to the code (maybe a rake task) that runs the data manipulation within the migration, since you have to run the 2nd migration right after the data manipulation.

If it were me, I would create a rake task that manipulates the data. This will at least remove the code from the migration and allow you to run it manually if it were ever necessary. Then code your migration and include a call to that rake task. I honestly don't see what the big deal is about not using data manipulation in a migration. Especially when you have to do things in a specific order as you are doing. They are tied so closely together, so why completely separate them?

Upvotes: 1

Sam Coles
Sam Coles

Reputation: 4043

Unless I misunderstand your question, the migration is the place to make that transformation. The purpose of the migration is to change your schema and migrate existing data to use the schema. Migrations capture the temporal aspect of layering schema changes, so that you can go forward and backward in time without leaving data in an inconsistent state. If you were to migrate your rows anywhere else, you have no guarantee that when that code runs, the schema is as it was when you wrote your migration code.

I believe that you will find support for my position in the examples on the Active Record Migrations api documentation. You might be confusing migrations with populating seed data (rake db:seed) which is handled in db/seeds.rb.

Upvotes: 2

Related Questions