moyinho20
moyinho20

Reputation: 624

How to copy other column's value as default value for a new column in rails migration?

I have a model with a column price. I need to add a new_column marked_price having value of price as it's default value. Can I write this in my migration, or what could be the best way to do this?

Something like:

class AddMarkedPriceToMenuItems < ActiveRecord::Migration
  def change
    add_column :menu_items, :marked_price, :decimal, :default => :price
  end
end

Upvotes: 23

Views: 9540

Answers (2)

Wilson Varghese
Wilson Varghese

Reputation: 147

This is a General way of solving, without the need for Writing Query, as queries are subjected to risk.

class Demo < ActiveRecord::Migration
  def change
    add_column :events, :time_zone, :string
    Test.all.each do |p|
      p.update_attributes(time_zone: p.check.last.time_zone)
    end
    remove_column :sessions, :time_zone
  end
end

Upvotes: 0

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

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.

Upvotes: 32

Related Questions