joshmn / caffeinate

A Rails engine for drip campaigns/scheduled sequences and periodical support. Works with ActionMailer, and other things.
https://caffeinate.email
MIT License
345 stars 13 forks source link

Generated migration throws error on rollback #11

Closed jameshbush closed 2 years ago

jameshbush commented 3 years ago

lib/generators/caffeinate/templates/migrations/create_caffeinate_campaign_subscriptions.rb.tt can be changed as follows to avoid this rollback error:

  #
  #    (3.6ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  #    (1.2ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  #    (1.0ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  #    (0.4ms)  SELECT pg_try_advisory_lock(8721676743767584905)
  #    (1.0ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  # Migrating to CreateCaffeinateCampaignSubscriptions (20211101175308)
  #    (0.5ms)  BEGIN
  # == 20211101175308 CreateCaffeinateCampaignSubscriptions: reverting ============
  #    (0.4ms)  ROLLBACK
  #    (0.3ms)  SELECT pg_advisory_unlock(8721676743767584905)
  # rake aborted!
  # StandardError: An error has occurred, this and all later migrations canceled:
  #
  #
  #
  # To avoid mistakes, drop_table is only reversible if given options or a block (can be empty).

Using up and down methods instead of change

# frozen_string_literal: true

class CreateCaffeinateCampaignSubscriptions < ActiveRecord::Migration[5.2]
  def up
    drop_table :caffeinate_campaign_subscriptions if table_exists?(:caffeinate_campaign_subscriptions)

    create_table :caffeinate_campaign_subscriptions do |t|
      t.references :caffeinate_campaign, null: false, index: { name: :caffeineate_campaign_subscriptions_on_campaign }, foreign_key: true
      t.string :subscriber_type, null: false
      t.integer :subscriber_id, null: false
      t.string :user_type
      t.integer :user_id
      t.string :token, null: false
      t.datetime :ended_at
      t.string :ended_reason
      t.datetime :resubscribed_at
      t.datetime :unsubscribed_at
      t.string :unsubscribe_reason

      t.timestamps
    end
    add_index :caffeinate_campaign_subscriptions, :token, unique: true
    add_index :caffeinate_campaign_subscriptions, %i[caffeinate_campaign_id subscriber_id subscriber_type user_id user_type ended_at resubscribed_at unsubscribed_at], name: :index_caffeinate_campaign_subscriptions
  end

  def down
    drop_table :caffeinate_campaign_subscriptions if table_exists?(:caffeinate_campaign_subscriptions)
  end
end