Changing the type of a column in mysql

I need to change the type of a column (wasserstand) from string to
integer, which already contains text.

My idea is to copy the string into a new scratch column, modify the
column type to integer and then manually set the appropriate ints.

After this, I want to remove the scratch string column in the next
migration.

The first migration should be done like this:

def self.up
tz = Teilzaehlung.all
ws = []
tz.each do |b|
ws << [b.id, b.wasserstand]
end

change_column(:teilzaehlungs, :wasserstand, :integer)
add_column(:teilzaehlungs, :wst, :string)

ws.each do |b|
  beob = Teilzaehlung.find(b[0])
  beob.update_attribute(:wasserstand, 0)
  beob.update_attribute(:wst, b[1])
end

end

Interestingly, after running the migration, the new interger typed
column contains 0, but the scratch column wst is always NULL - even if
b[1] contains a string.

Why?

Edit: Even writing
beob.update_attribute(:wst, “test”)
results in wst = NULL

No modification of wst within the migration succeeds, while
modifications of already existing columns succeed.

Solution:
Split the migration: The first creats the new column, the second
processes the data.

Looks like problem with migrations.

On Oct 31, 11:01am, Fritz T. [email protected] wrote:

Solution:
Split the migration: The first creats the new column, the second
processes the data.

Looks like problem with migrations.

Classes cache column information, but you can call
MyClass.reset_column_information to clear that cache.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs