Search code examples
ruby-on-railsruby-on-rails-5rails-migrations

How do I reversibly remove_foreign_key on a table when the column doesn't match the table?


I tried the following

remove_foreign_key :users, :asset_types, column: :seek_asset_type_id

But got the error

StandardError: An error has occurred, this and all later migrations canceled:
wrong number of arguments (given 3, expected 1..2)

The documentation says it uses the same options as #add_foreign_key.

Documentation

The column was created previously with

add_reference :users, :seek_asset_type, foreign_key: {to_table: :asset_types}

This is the definition:

"fk_rails_4dcaa1c59c" FOREIGN KEY (seek_asset_type_id) REFERENCES asset_types(id)

Solution

  • Use revert:

    def change
      revert do
        add_reference :users, :seek_asset_type, foreign_key: { to_table: :asset_types }
      end
    end
    

    Another way is to revert a migration by its name:

    def change
      revert AddAssetTypeReferenceToUsers 
      # I made up this migration name, 
      # so please fill in the appropriate name
    end