如何在Rails的迁移中编写SQL [英] How to write SQL in a migration in Rails

查看:79
本文介绍了如何在Rails的迁移中编写SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下SQL

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;

由于我无法使用heroku数据片段删除表,因此无法使用数据片段.

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.

如何将此sql编写为迁移文件?

How do I write this sql as a migration?

推荐答案

对于您的向上迁移:

execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users;" 
drop_table :car_users  
rename_table :car_users2, :car_users  

然后向下:

raise ActiveRecord::IrreversibleMigration

完全迁移:

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

这篇关于如何在Rails的迁移中编写SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆