Migration Issues: Can't update newly added column values

Hello everyone, just wondering if anyone can help me with a migrations question here.

Using:   rails 2.0.2   ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin]   mysql 5.0.45 Platform:   windows xp

The problem:

Does this version work for you?

class AddDeletedAtToOptions < ActiveRecord::Migration    class Option < ActiveRecord::Base; end

   # Add `deleted_at` column, set to Time.now if `is_deleted` is true,    # then remove `is_deleted`:

How about something like this:

  def self.up     add_column(:options, :deleted_at, :timestamp, :default => nil)     say "IN TABLE option: Setting `deleted_at` to now if `is_deleted`." do       Option.update_all("deleted_at = '#{Time.now}' ", "is_deleted==1")     end     remove_column(:options, :is_deleted)   end

There's no need to iterate over the objects in Ruby -- delegate that to the DB.

I don't know if anyone cares, but just for closure (and for those who may have a similar issue and search the newsgroup), here is an update with my issue.

I tried both recommendations made previously by both Rob and AndyV to no avail. In both cases, the migration ran, reporting success. However, the values in the `deleted_at` column were NULL, even for the record that should have had a timestamp. I don't understand why this works the way it does. I'd think that either the migration would fail on the "Option.update_all(...)" line due to an SQL error on the database or something (if the created column hadn't actually been created yet) or that the actual migration would truly work as expected. If anyone figures this out (or already knows what's going on) feel free to let us know for curiosity sake.

As for me, I ended up just sidestepping the problem. Instead of continuing research on the issue (like reading/tracing ActiveRecord code) I just rewrote my actual fixtures to reflect the latest schema and I load them after all migrations have run. I can get away with this since I'm still in the early stages of development and have no 'live' non-fixture data to worry about.

Thanks to those who tried to help.

Kendall wrote:

I don't know if anyone cares, but just for closure (and for those who may have a similar issue and search the newsgroup), here is an update with my issue.

In case anyone finds this which Googling the same problem (like I did) this blog post has the answer:

Essentially you need to call reset_column_information on your model. For example

add_column 'my_models', 'new_column' MyModel.reset_column_information my_model = MyModel.first my_model.new_column = 'this will save' my_model.save