How to write SQL in a migration in Rails

后端 未结 4 1208
醉话见心
醉话见心 2021-01-01 08:41

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 R         


        
4条回答
  •  醉话见心
    2021-01-01 09:02

    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.

提交回复
热议问题