Veerasundaravel's Ruby on Rails Weblog

February 8, 2008

ActiveRecord reload in Migration


Today I faced one problem , Like I want to add one column in existing model user. And want to update the field value in next line itself as follows:

class CreateAdminStructure < ActiveRecord::Migration
def self.up
add_column :users, :admin_flag, :boolean, :default=>false
user=User.find(1)
user.admin_flag=true
user.save!
end

def self.down
remove_column :users, :admin_flag
end
end

So when I’m trying to assign a value to newly added field admin_flag like ‘user.admin_flag=true’, it return some error like unknown column admin_flag.

The problem is newly added admin_flag column in users table will not come to effect within the same migration file on that instance. So to avoid this issue we might reload the table structure.

So when ever you are trying to update/access newly added fields within migration, you have to tell the ActiveRecord about the changes.
For that we have one option like
.reset_column_information

You can use the .reset_column_information to force ActiveRecord to notice the changes that the migration has made to the database.

class CreateAdminStructure < ActiveRecord::Migration
def self.up
add_column :users, :admin_flag, :boolean, :default=>false
User.reset_column_information
user=User.find(1)
user.admin_flag=true
user.save!
end

def self.down
remove_column :users, :admin_flag
end
end


Reference Url:

            http://railsapi.org/activerecord-base-reset_column_information

Advertisements

1 Comment »

  1. Goede informatie, hier kan ik erg veel mee bedankt!

    Comment by Mariann Oborny — December 6, 2011 @ 2:02 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: