What's the correct syntax for remove_index in a Rails 3.1.0 migration?

后端 未结 6 911
清歌不尽
清歌不尽 2021-02-01 00:30

I\'m in the process of adding Devise to an existing Rails app, with a Users table already defined. The devise generator pushed out the following migration:

class         


        
6条回答
  •  旧时难觅i
    2021-02-01 01:01

    I'd like to expand on @iWasRobbed's answer. If you have index on just single column then worrying about remove_index doesn't make sense since (just an assumtion!) the DB should be smart enough to cleanup the resources used by that index. But in case you have multiple columns index removing the column will reduce index to still existing columns, which is totally sensible thing to do, but kind of shows where you might want to use remove_index explicitely.

    Just for illustration - migration below has that flaw that after being applied up and down it will leave the unique index on email (meaning the down part is not doing its job properly)

    class AddIndexes < ActiveRecord::Migration
      def up
        add_column :users, :action_name, :string
        add_index  :users, [:email, :action_name], unique: true
      end
    
      def down
        remove_column :users, :action_name
      end
    end
    

    Changing the down block to

      def down
        remove_index :users, [:email, :action_name]
        remove_column :users, :action_name
      end
    

    will fix that flaw and allow the migration to correctly return DB to the previous state with rake db:rollback

提交回复
热议问题