如何在Rails中的迁移中编写SQL

问题描述 投票:48回答:4

我有以下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写为迁移?

sql postgresql ruby-on-rails-3 migration rails-activerecord
4个回答
95
投票

对于您的向上迁移:

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

17
投票

你可以尝试使用execute方法。

这样的事情(它是未经测试的,某种想法)

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


4
投票

我更喜欢这里的文档:

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


4
投票

如果您需要使用change而不是updown,您可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.