Function on Migrations

can migration able to used for edit, delete, alter, or any else look like SQL? because i see it seems make a querry in “ruby way” is easier than make a querry in SQL

thanks before :smiley: Start

yes, this is possible.

I have read that it is not advised to do this, with no reasons given, but I myself have had good experience incorporating data manipulation statements in migrations.

Since a typical deployment procedure (e.g. Capistrano) runs migrations, I have had good experience restructuring database tables and populating the new table set during a migration. Of course, such a migration is probably not reversible, but in practice that has not been a problem for me.

One advantage to populating table fields in migrations is that it can be structured to occur after some particular previous migration or before some particular subsequent migration. This is sometimes essential in a complicated database restructuring.

I have found it useful too to delegate this type of activity from a migration to a model, so that it can be thoroughly tested.

Les

The problem is using your Rails models to generate those SQL statements (update/insert/delete), not "execute custom_sql".

The problem is that your models is constantly changing so your migration may mean something today but could perform a different operation later on when you've modified your model and then the migration result won't be the same depending on when you run them.

This is why it's not advisable to use your models inside the migrations.

That’s why we write tests, so that the model behaves the same today and 1 year from today.

In my experience, migrations have an active lifetime of no more than a few days. Perhaps others use them differently. My apps have hundreds of migrations, most of them were run in production just once.

Les

The model will only behave the same today as it will in a year if your application is complete and you don’t write any code (or tests) in the next year.

If you do write code you might add a validation, and a test for that validation. Then the migration can fail.

If you are working on a large enough team the validation might be released between the time when you write the migration and the time when you deploy your change. That might even happen if you are a team of one and you working on a long feature.

It is much safer to write a rake task and run that rake task on the server when you need it. Unwinding a partially complete migration on a production database is not pleasant.

Ray