Wednesday, December 31

Qucik Fix: ActiveRecord Migrations reset_column_information

Few days back I had created few migrations that would rename existing table and again create a table with old name.
  1. user should be renamed as "old_users" 
  2. create a new table "user"
  3. restore the data with different column names in the "user"

  def self.up
    rename_table :users, :old_users
    create_table :users do |t|
      t.column :created_at, :datetime
    end  

    Temp.find(:all).each do |user|
      new_user = User.new(:id=> user.id, :created_at => user.created_at)
      new_user.save!
    end
  end

Don't worry about the Temp, Temp is a class through which I am accessing the old_users table.  Precisely,

class Temp <>
  set_table_name "old_users"
end

This worked pretty well in my local environment and when I deployed in staging, it crashed.  The error was that, it was trying to insert data into table with prvious structure/columns.  Which means, the new structure hasn't taken effective.

The quick fix seems to be reset_column_information.  Before pushing/creating fresh data in the table, I need to reset the column information of the tables.  So including the following line:
      User.reset_column_information
right before creating new users solved the problem.

By the way "WISH YOU HAPPY AND PROSPEROUS NEW YEAR"

No comments: