How to copy other column's value as default value for a new column in rails migration?
No, the database does not allow you to do this using the DEFAULT
setting on a table column.
But you can do it using an ActiveRecord callback
class MenuItem < ActiveRecord::Base
before_create :set_market_price_default
private
def set_market_price_default
self.market_price = self.price
end
end
As for the migration itself, you can update market_price
manually
def change
add_column :menu_items, :marked_price, :decimal
reversible do |dir|
dir.up { MenuItem.update_all('marked_price = price') }
end
end
Note that you might want to create a copy of the model that sits locally in the migration, so that it doesn't go out of sync in the future.