ALTER TABLE lhm migration deletes existing values

require 'lhm'

class RenameField1ToField2ForTable < ActiveRecord::Migration
  def up
    Lhm.change_table :table do |m|
      m.ddl("ALTER TABLE %s CHANGE COLUMN field1 field2 FLOAT DEFAULT NULL AFTER field3" m.name)
    end
  end

  def down
    Lhm.change_table :table do |m|
      m.ddl("ALTER TABLE %s CHANGE COLUMN field2 field1 FLOAT DEFAULT NULL AFTER field3" m.name)
    end
  end
end

What happend:

  1. Rails-4.0: rake db:migrate
  2. Field was renamed successfully.
  3. All existing field values are erased, why? Any ideas?

Edit:

  • old datatype was float(11)
  • MYSQL 5.6

Answers


I would highly suggest you utilize the methods made available to you from LHM that mimic the ones from Rails (if you plan to use LHM):

Lhm.change_table(:users) do |m|
  m.change_column(:old_column, :float)
  m.rename_column(:old_column, :new_column)
end

If you look at the method definitions, you will see LHM is doing a MODIFY where you are doing a CHANGE for change_column, and a CHANGE for rename_column.

Official Docs:

change_column: https://docs.omniref.com/ruby/gems/lhm/2.2.0/symbols/Lhm::Migrator/change_column?d=415590290&n=0#

rename_column: https://docs.omniref.com/github/soundcloud/lhm/2.2.0/symbols/Lhm::Migrator/rename_column?d=409846811&n=4#


Can you do a straight rails migration like so:

def change
  rename_column :table_name, :old_column, :new_column
end

I've never used lhm so this might not be possible?

Also you might not need the "FLOAT DEFAULT NULL" in your current SQL statement if it's already specified in the DB.

Hope that helps.


rename 1st_name to temporary_name, and then rename 2nd_name to 1st_name, and then rename from temporary_name to 2nd_name


Need Your Help

format hex string using replace, regex and notepad++

regex replace hex notepad++

Given an hex string, which is unformatted, e.g.

How do I find the alias for an index in ElasticSearch

elasticsearch

I would like to find out the alias for a given index in ElasticSearch. Basically, the reverse of this question: How to find Index by Alias in Elasticsearch java api?