【问题标题】:Rails How to Revert Migration Change?Rails 如何恢复迁移更改?
【发布时间】:2015-06-16 18:48:59
【问题描述】:
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'

【问题讨论】:

    标签: ruby-on-rails activerecord devise migration


    【解决方案1】:

    自定义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
    

    【讨论】:

    • 我尝试了底部代码,但它不起作用。我不确定上面的代码是什么意思。
    • 可能是您的索引命名index_users_on_email,可能与add_indexremove_index 的约定名称不同。
    猜你喜欢
    • 1970-01-01
    • 2011-12-03
    • 2015-03-25
    • 2015-11-14
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2011-05-22
    相关资源
    最近更新 更多