Rails How to Revert Migration Change?

191 Views Asked by At
class UpdateIndexOnUsers < ActiveRecord::Migration
  def change
    sql = 'DROP INDEX index_users_on_email'
  sql << ' ON users' if Rails.env == 'production' # Heroku pg
  ActiveRecord::Base.connection.execute(sql)
  end
end

Is there a way to change this back with one migration rather than rolling back?

EDIT: Tried to rake db:migrate:down VERSION=20150611173755 but didn't work.

PG::UndefinedObject: ERROR:  index "index_users_on_email" does not exist
: DROP INDEX index_users_on_email/Users/goda/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `block in log'
/Users/tingaloo/.rvm/gems/ruby-2.2.1@global/gems/activesupport-4.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:460:in `log'
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:154:in `execute'
/Users/tingaloo/rails/novelshare/db/migrate/20150611173755_update_index_on_users.rb:5:in `change'
1

There are 1 best solutions below

2
On

Custom SQLis not reverisble.

But you can change it to be:

def up
  sql = 'DROP INDEX index_users_on_email'
  sql << ' ON users' if Rails.env == 'production' # Heroku pg
  ActiveRecord::Base.connection.execute(sql)
end

def down
  ** code to add the index back **
end

But I think that you should use Rails-Syntax:

def up
  remove_index :users, :email if Rails.env == 'production'
end

def down
  add_index :users, :email
end