How to set a value for a new column in Rails 3?

This is probably in a different question, but I cannot find it.

I am noobie for Rails. I am trying to add a new column to a table that already has data. This column will not allow null. What is the easiest way to update all existing records to make a difference in this new column? I know this is probably in the top block of my migration, but I don't know what the syntax will be.

def self.up change_table :reminders do |t| t.boolean :active end #model name is Reminder - how to update data with a value? end 
+4
source share
2 answers

What you can do is add a column, update all the records in the table with the desired value, and then change it to not allow zeros.

 def self.up add_column :reminders, :active, :boolean, :default => true Reminder.update_all( "active = ?", true ) change_column :reminders, :active, :boolean, :default => true, :null => :false end 
+7
source

Try the following:

 def self.up change_table :reminders do |t| t.boolean :active, :default => true #or your value end #model name is Reminder - how to update data with a value? end 
0
source

All Articles