I'm just learning Rails and have begun the section on database migrations. I built 2 migrations and both migrated up successfully. Migrating down, the latest migration, the one that runs first, failed because of a typo in my code. I fixed the typo but the migration continued to fail after that. I discovered the reason why was that the migrating down aborted half way through changes and then when I tried to migrate down again it failed because some of the changes had already been made and so column names were different and other issues like that. I ended up fixing it by fiddling with the schema_migrations
table and manually rolling back my changes to a previous version and then migrating back up and down from there.
My question is, is there a way to tell Rails to run migrations in transaction mode and if the code fails, not to commit the transaction?
On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.
When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.
Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.
It adds a multi-column index on columns one and two in resources table. The advantage of multi-column index is that it helps when you have a query with conditions on those multiple columns.
Rails will already run your migrations inside a transaction if your database supports it:
On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.
It's up to you to use a database that respects transactions when performing schema changes. MySQL (as far as I know) doesn't, but Postgres absolutely does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With