4 database migration postgresql ruby-on-rails rails-activerecord
我正在使用Rails 4.2.7.我想创建一个启用扩展的迁移,但前提是我正在运行的主机环境中不存在该扩展.我创造了
class EnableUuidOsspExtension < ActiveRecord::Migration
def change
enable_extension 'uuid-ossp'
end
end
Run Code Online (Sandbox Code Playgroud)
但是如果已经启用了扩展,我想禁止启用扩展.如何调整上述迁移才能实现此目的?这样做的动机是因为在我的本地机器上我必须运行它才能将它添加到PostGres,但是如果我迁移到Heroku,这个扩展可能已经到位,但是当我运行db迁移时我不想让事情崩溃脚本.
有一个extensions方法返回一个扩展名数组,所以你可以这样做:
def up
enable_extension('uuid-ossp') unless extensions.include?('uuid-ossp')
end
def down
disable_extension('uuid-ossp') if extensions.include?('uuid-ossp')
end
Run Code Online (Sandbox Code Playgroud)
您也可以在SQL中手动执行此操作,您可以访问create extension if not exists:
def up
connection.execute('create extension if not exists "uuid-ossp"')
end
Run Code Online (Sandbox Code Playgroud)
在新的 Rails 中,您不需要明确指定它
只需使用这样的语法
def change
enable_extension :pgcrypto
end
Run Code Online (Sandbox Code Playgroud)
它生成 SQL 查询
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
Run Code Online (Sandbox Code Playgroud)
并且当回滚时
DROP EXTENSION IF EXISTS "pgcrypto" CASCADE;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1375 次 |
| 最近记录: |