如何在Rails中进行迁移编写SQL

我有以下SQL我需要做的

CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users; DROP TABLE cars_users; ALTER TABLE cars_users2 RENAME TO cars_users; 

因为我不能使用heroku dataclips来删除一个表,我不能使用dataclips。

所以我想我需要在迁移中做到这一点。

我如何写这个SQL作为迁移?

对于你的升迁:

 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 

你可以尝试使用execute方法。

像这样的东西(这是未经testing的,某种心思)

 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 

由于没有相应的down方法,因此在尝试迁移时应该引发ActiveRecord::IrreversibleMigration

如果你需要使用change而不是down你可以使用reversible 。 它适用于Rails 4或以上。

 class ExampleMigration < ActiveRecord::Migration def change create_table :distributors do |t| t.string :zipcode end reversible do |dir| dir.up do # add a CHECK constraint execute <<-SQL ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT; SQL end dir.down do execute <<-SQL ALTER TABLE distributors DROP CONSTRAINT zipchk SQL end end add_column :users, :home_page_url, :string rename_column :users, :email, :email_address end end 

来源: http : //edgeguides.rubyonrails.org/active_record_migrations.html#using-reversible

https://apidock.com/rails/ActiveRecord/Migration/reversible

我更喜欢这里doc:

 execute <<-SQL CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users; DROP TABLE cars_users; ALTER TABLE cars_users2 RENAME TO cars_users; SQL 

注意:这只适用于PostgreSQL ,如果你正在使用MySQL,你应该为适配器设置CLIENT_MULTI_STATEMENTS 。