Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 771
SG 86 Avatar asked Mar 14 '16 10:03

SG 86


1 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#

like image 128
omarvelous Avatar answered Nov 10 '22 18:11

omarvelous