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

查看:23
本文介绍了如何在 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天全站免登陆