Forum: Ruby on Rails Changing the type of a column in mysql

1d2a3db8a120372034ce9dc2c293d203?d=identicon&s=25 Fritz Trapper (trapper)
on 2010-10-30 22:55
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.
1d2a3db8a120372034ce9dc2c293d203?d=identicon&s=25 Fritz Trapper (trapper)
on 2010-10-31 12:01
Solution:
Split the migration: The first creats the new column, the second
processes the data.

Looks like problem with migrations.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2010-10-31 19:16
(Received via mailing list)
On Oct 31, 11:01am, Fritz Trapper <li...@ruby-forum.com> 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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.