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
If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.
just require the file with the class, e.g. in the console: require "./db/migrate/20150927161307_create_users. rb" instead of copy & pasting. You can then run the class the same way by instantiating and calling the method defined in the class CreateUsers.
index: true vs foreign_key:true in migration When we write index: true to any column, it adds a database index to this column. Foreign key enforce referential integrity. In the example above we have profile_id column in educations table which is foreign key of profiles table.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With