Rails如何恢复迁移变化?

时间:2015-06-16 18:48:59

标签: ruby-on-rails activerecord devise migration

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

有没有办法通过一次迁移而不是回滚来改变它?

编辑:尝试rake db:migrate:down VERSION=20150611173755,但没有效果。

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 个答案:

答案 0 :(得分:0)

自定义SQL不会产生任何影响。

但您可以将其更改为:

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

但我认为你应该使用Rails-Syntax:

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

def down
  add_index :users, :email
end