如何在此迁移中编写向下或可逆函数?

时间:2013-08-10 06:32:22

标签: ruby-on-rails ruby-on-rails-3 postgresql ruby-on-rails-4

因此,如果此迁移导致任何错误,我希望能够恢复/ rake db:rollback。

代码:

class ChangeUidToPrimaryKey < ActiveRecord::Migration
def change
execute ALTER TABLE "users" DROP CONSTRAINT "users_pkey".
execute ALTER TABLE "users" ADD PRIMARY KEY "uid"
end
end

在这种情况下,我可以添加什么向下/可逆代码来使rake db:rollback工作?

1 个答案:

答案 0 :(得分:1)

如果您需要恢复,可以执行以下操作,即在email上保留唯一索引。

class ChangeUidToPrimaryKey < ActiveRecord::Migration
  def self.up
    execute "alter table users add constraint unique_users_email unique(email)"
    execute "ALTER TABLE users DROP CONSTRAINT users_pkey"
    execute "ALTER TABLE users ADD PRIMARY KEY (uid)"
  end

  def self.down
    execute "ALTER TABLE users DROP CONSTRAINT users_pkey"
    execute "ALTER TABLE users DROP CONSTRAINT unique_users_email"
    execute "ALTER TABLE users ADD PRIMARY KEY (email)"
  end
end