I want to add a column called "payment_type" into my "orders" table.
Here is the migration that I have so far:
add_column :orders, :payment_type, :string
I want that payment_type to hold the value "normal" for all the records that currently are in the DB. However, not for the future records. I want no default value for future records. How can I do this?
As you just want to set values for all existing records, you can use
update_all, which is much faster than looping over all instances of order, as it uses just database statements and doesn't instanciate all the orders:
def up add_column :orders, :payment_type, :string Order.reset_column_information Order.update_all(payment_type: 'normal') end def down remove_column :orders, :payment_type end
update_all does not call any validations or triggers.
def change add_column :orders, :payment_type, :string Order.all.each do |order| order.update_attributes(:payment_type => 'normal') end end
If you want to updated column stick with migration then above answers is awesome, But if you want to update column locally on your own machine so that when you shear code others unable to see updated attribute, simple go to Rails console and loop...
orders = Order.all orders.each do |o| o.update_attribute(:payment_type, 'normal') end