50
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マイグレーションで remove_index の際には column オプションをサボらない

Last updated at Posted at 2016-01-27

rake db:migrate して、検証のために rake db:rollback したところエラーで怒られたのでシェア

環境

  • Ruby : ruby 2.2.3p173
  • Rails : Rails 4.2.1

状況

既存のインデックスにUNIQUEインデックスに変更したかったので以下のような migration を書いた

class AddUniquenessToCompanies < ActiveRecord::Migration
  def change
    remove_index :companies, :url
    add_index    :companies, :url, unique: true
  end
end

migrate 実行。。。

$ rake db:migrate

== 20160124130800 AddUniquenessToCompanies: migrating ===================
-- remove_index(:companies, :url)
   -> 0.0142s
-- add_index(:companies, :url, {:unique=>true})
   -> 0.1733s
== 20160124130800 AddUniquenessToMyModel: migrated (0.1876s) ==========

rollback の確認をっと、、、

$ rake db:rollback

== 20160124130800 AddUniquenessToMyModel: reverting ===================
rake aborted!
StandardError: An error has occurred, all later migrations canceled:



remove_index is only reversible if given a :column option.

/Users/kawakubox/Workspace/my-rails-project/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/command_recorder.rb:157:in `invert_remove_index'
/Users/kawakubox/Workspace/my-rails-project/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/command_recorder.rb:66:in `inverse_of'
/Users/kawakubox/Workspace/my-rails-project/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/command_recorder.rb:50:in `record'
/Users/kawakubox/Workspace/my-rails-project/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/command_recorder.rb:83:in `remove_index'

!!!

remove_index is only reversible if given a :column option.

remove_index は :column オプションが指定されている場合のみ戻せるよ

と言われてる

回避策

1. 指摘通りに column オプションをつける

class AddUniquenessToCompanies < ActiveRecord::Migration
  def change
    remove_index :companies, column: :url
    add_index    :companies, :url, unique: true
  end
end

※複数カラムの場合は column: [:hoge, :piyo] と配列にする

2. change ではなく up, down にする

class AddUniquenessToCompanies < ActiveRecord::Migration
  def up
    remove_index :companies, :url
    add_index    :companies, :url, unique: true
  end

  def down
    remove_index :companies, :url
    add_index    :companies, :url
  end
end

所感

  • migration 作ったら、 rake db:migrate だけでなく、 rake db:rollback も検証しよう。
50
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?