Thursday, March 24, 2016

ALTER TABLE lhm migration deletes existing values

Leave a Comment
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

3 Answers

Answers 1

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#

Answers 2

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.

Answers 3

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment