mysql – 恢复迁移时的ActiveRecord :: IrreversibleMigration异常
作者:互联网
我创建了以下Active Record Migration,它添加和删除了一些索引.
class FixIndexes < ActiveRecord::Migration
def change
add_index :table1, :field1, :unique => true
remove_index :table2, :name => "index_table2_on_field1"
remove_index :table2, :name => "index_table2_on_field2"
remove_index :table3, :name => "index_table3_on_field1"
add_index :table3, [:field1, :field2]
end
end
当我运行迁移($bundle exec rake db:migrate)时,它可以正常工作.
不幸的是,当我尝试恢复迁移($bundle exec rake db:rollback)时,它不起作用并引发ActiveRecord :: IrreversibleMigration异常
== FixIndexes: reverting =====================================================
rake aborted!
An error has occurred, all later migrations canceled:
ActiveRecord::IrreversibleMigration/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:42:in `block in inverse'
/usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-3.2.14/lib/active_record/migration/command_recorder.rb:40:in `map'
我的问题是:
>为什么这是不可逆转的迁移?它只是添加和
删除一些索引,而不是数据.
>如果我使用def self.up和def self.down,它将解决问题
而不是改变?
>如何在不添加和删除的情况下立即恢复此更改
从MySQL手动索引?
解决方法:
在Rails中只有少数命令是可逆的(没有手动命令).他们是
> add_column
> add_index
> add_timestamps
> create_table
> create_join_table
> remove_timestamps
> rename_column
> rename_index
> rename_table
参见here
您的迁移包含remove_index,CommandRecorder for Rollback不支持该删除.
如果你查看这个Documentation
Some transformations are destructive in a manner that cannot be
reversed. Migrations of that kind should raise an
ActiveRecord::IrreversibleMigration exception in their down method.
你的情况就是这样,显然会导致ActiveRecord :: IrreversibleMigration异常.
长话短说:如果没有手动命令,remove_index无法撤消.
标签:ruby-on-rails,activerecord,mysql,ruby-on-rails-3,rails-migrations 来源: https://codeday.me/bug/20190831/1772506.html