Search code examples
ruby-on-railsmigration

Is it possible to rename an index using a rails migration?


I know that there is a rename_column transformation, but it seems that rename_index does not exist.

Do I have to use remove_index and add_index instead?


Solution

  • You can execute arbitrary SQL in your migrations as well.

    We have some helper methods that add foreign keys to our tables:

    def add_foreign_key(from_table, from_column, to_table)
      constraint_name = "fk_#{from_table}_#{from_column}"
    
      execute %{alter table #{from_table}
                add constraint #{constraint_name}
                foreign key (#{from_column})
                references #{to_table}(id)
               }
      end
    

    You can use any SQL your database supports.