How to write SQL in a migration in Rails

Nick Ginanto picture Nick Ginanto · Feb 13, 2013 · Viewed 43.1k times · Source

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?

Answer

Tomdarkness picture Tomdarkness · Feb 13, 2013

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