I have the following SQL which I need to do
CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users; DROP TABLE cars_users; ALTER TABLE cars_users2 RENAME TO cars_users;
since I cannot use heroku dataclips to drop a table, I cannot use dataclips.
So I guess I need to do this in a migration.
How do I write this sql as a migration?
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.
Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Teams of developers − If one person makes a schema change, the other developers just need to update, and run "rake migrate".
For your up migration:
execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users;" drop_table :car_users rename_table :car_users2, :car_users
and for down:
raise ActiveRecord::IrreversibleMigration
Full migration:
class TheMigration < ActiveRecord::Migration def up execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * from cars_users;" drop_table :car_users rename_table :car_users2, :car_users end def down raise ActiveRecord::IrreversibleMigration end end
You could try to use the execute
method.
Something like this (it's untested, some kind of brainchild)
class UpdateCarUserTable < ActiveRecord::Migration def up execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users" execute "DROP TABLE cars_users" execute "ALTER TABLE cars_users2 RENAME TO cars_users" end
As there is no equivalent down
method, an ActiveRecord::IrreversibleMigration
should be raised when trying to migrate down.
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