views:

93

answers:

2

I have created this migration in Rails:

class AddSocialSecurityNumberToContactTable < ActiveRecord::Migration
  def self.up
    add_column :contacts, :ss_number, :string
  end

  def self.down
    remove_column :contacts, :ss_number
  end
end

In my development database, which is a SQLite3 database, all the old Contact records gained the ss_number field, just nil. However, whenever I deploy the code with migrations, the old, pre-migration Contact records do not have a ss_number field. I have restarted the server and logged into the console and verified it both ways on both a production database (MySQL) and a staging database (MySQL).

If, however, I create a new record in the console, it does show a ss_number field for the Contact object.

>> a = Contact.find(1)
=> #<Contact id: 1, first_name: "Gary", last_name: "Simpson", email: "", home_phone: "", work_phone: "", mobile_phone: "", mailing_street: "123 Main St", mailing_street_2: "", mailing_city: "Little Rock", mailing_state: "AR", mailing_zip: "72205", created_by: 1, created_at: "2010-07-24 19:30:10", updated_at: "2010-07-24 19:30:10">
>> a.ss_number
ActiveRecord::MissingAttributeError: missing attribute: ss_number
 from /srv/www/domain/releases/20100727004056/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:217:in `send'
 from /srv/www/domain/releases/20100727004056/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:217:in `method_missing'
 from (irb):4
>> a = Contact.new
=> #<Contact id: nil, first_name: nil, last_name: nil, email: nil, home_phone: nil, work_phone: nil, mobile_phone: nil, mailing_street: nil, mailing_street_2: nil, mailing_city: nil, mailing_state: nil, mailing_zip: nil, created_by: nil, created_at: nil, updated_at: nil, ss_number: nil>
>> a.ss_number
=> nil

How can I make it so that all existing Contact rows have nil as their value after I migrate?

A: 

Hi Geoffrey,

You can add Find statments and blocks to your migration code, so you could do something like this:

  def self.up
    add_column :contacts, :ss_number, :string
    Contacts.find(:all).each do |contact|
      contact.ss_number = nil
      contact.save
    end
  end

Hope this helps!

Alternatively, I believe you could just do this:

add_column :contacts, :ss_number, :string, :null=>true

The

:null=>true

at the end will set it as the default as it adds the column to the table.

Canuk
A: 

Thanks to Jesse's comment above, I have tracked down that the culprit was indeed memcached, which makes total sense. Thanks, Jesse!

Geoffrey Lessel