如何在Rails迁移中使触发器可逆

问题描述 投票:0回答:2

我正在用Ruby on Rails编写迁移,其中包含触发器,当我回滚时出现以下错误:

ActiveRecord::IrreversibleMigration: 

This migration uses execute, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.

我在变更函数中定义了所有表和触发器:

class Geolocation < ActiveRecord::Migration[5.0]
    def change
     [...]
     execute <<-SQL
        CREATE OR REPLACE FUNCTION zone_preset_jolly_city() RETURNS trigger
        LANGUAGE plpgsql AS 
        $$BEGIN
          INSERT INTO cities( zone_preset_id, name ) VALUES ( NEW.zone_id, '%' );
          RETURN NEW;
        END;$$;

        CREATE OR REPLACE FUNCTION city_jolly_toponym() RETURNS trigger
        LANGUAGE plpgsql AS 
        $$BEGIN
          INSERT INTO toponyms( city_id, toponym_type_id, name ) VALUES ( NEW.city_id, '%', '%' );
          RETURN NEW;
        END;$$;

        CREATE OR REPLACE FUNCTION toponym_jolly_street_number() RETURNS trigger
        LANGUAGE plpgsql AS 
        $$BEGIN
          INSERT INTO street_numbers( toponym_id, number ) VALUES ( NEW.toponym_id, '%' );
          RETURN NEW;
        END;$$; 

        CREATE TRIGGER zone_preset_jolly
          AFTER INSERT ON zone_presets
          FOR EACH ROW EXECUTE PROCEDURE zone_preset_jolly_city();

        CREATE TRIGGER city_jolly_toponym
          AFTER INSERT ON cities
          FOR EACH ROW EXECUTE PROCEDURE city_jolly_toponym();

        CREATE TRIGGER toponym_jolly_street_number
          AFTER INSERT ON toponyms
          FOR EACH ROW EXECUTE PROCEDURE toponym_jolly_street_number();
      SQL
end

因此,我试图定义一个向上和向下功能以正确还原触发器,但我不知道如何将它们反转定义。有什么建议吗?

ruby-on-rails postgresql triggers migration
2个回答
1
投票
[如果您不关心使迁移中的数据更改可逆,则只需将更改方法重命名为up并设置一个空的down方法:

class Geolocation < ActiveRecord::Migration[5.0] # this used to be def change def up ... ... ... end def down end end

[如果您确实想使其可逆,那么您将需要逆转您在up方法中执行的所有事务,并在down方法中运行它们。但是,当然不是所有的事情都是完全可逆的。 

0
投票
我喜欢在这些情况下使用可逆性。

class MigrationName < ActiveRecord::Migration[5.2] def change reversible do |dir| dir.up do execute <<-SQL INSERT INTO users VALUES ('name'); SQL end dir.down do execute <<-SQL DELETE FROM users; SQL end end end end

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