I have a table with dates stored as unix timestamps (ints). I want my migration to move these ints to another column, change the type of the first column to datetime, then convert the ints to ruby times and stick them back in the first column. This is my migration:
def self.up
add_column :events, :start_date_int, :int
Event.all.each do |event|
event.start_date_int = event.start_date
event.save
end
change_column :events, :start_date, :datetime
Event.all.each do |event|
time = Time.at(event.start_date_int)
event.start_date = time
puts time
puts event.start_date
event.save
end
end
The terminal output is this:
== DatesToDates: migrating ===================================================
-- add_column(:events, :start_int, :int)
-> 0.2880s
-- add_column(:events, :end_int, :int)
-> 0.3138s
-- change_column(:events, :start, :datetime)
-> 0.2695s
-- change_column(:events, :end, :datetime)
-> 0.2959s
Sun May 01 13:00:00 -0400 2011
1304269200
== DatesToDates: migrated (1.2923s) ==========================================
(There is only 1 event in the development DB)
For some reason event.start_date = time trying to stick the int into event.start_date instead of the converted time. If I separate the second loop into another migration and run the two seperately (via db:migrate:up VERSION=X for each) everything works properly, but if both migrations run together via a normal db:migrate, even if they are in separate files, it fails as stated. Any ideas?
(This is rails 3 with MySQL)
You probably want to have a look at
reset_column_information. I’m guessing this is your issue since you mention that it works if you do the migrations separately, but not when run together.