class AddAndSetColumn < ActiveRecord::Migration def self.up add_column :nodes, :new_column_1, :boolean, :null => false, :default => false Node.find(:all).each do |n| n.new_column_1 = true n.save! end end def self.down remove_column :nodes, :new_column_1 end end
After running the migration, and looking at the database, all nodes had new_column_1 set to false, even though I explicitly set it to true in the migration.
After searching around to see why this happens, I found a posting that described this problem at http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/573cbb96b84f3306/a0d6a3c7dddbbbcb?lnk=raot. The solution for this is to call reset_column_information on the model for the table that you added the column to before you assign values. So I changed my migration to:
class AddAndSetColumn < ActiveRecord::Migration def self.up add_column :nodes, :new_column_1, :boolean, :null => false, :default => false Node.reset_column_information Node.find(:all).each do |n| n.new_column_1 = true n.save! end end def self.down remove_column :nodes, :new_column_1 end end
And it works!
No comments:
Post a Comment