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
Related Articles
- Ruby on Rails ActiveRecord: Part 1 [Video Tutorial] (thinkvitamin.com)
- 5 Rails Plugins to Help Optimize Your MySQL | Purify Blog (purifyapp.com)