Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 872
moyinho20 Avatar asked Jan 19 '17 13:01

moyinho20


People also ask

Can you edit a migration file rails?

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.

How do I migrate a specific migration in rails?

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.

What is index true in rails migration?

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.


1 Answers

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.

like image 128
Mihai Dinculescu Avatar answered Sep 17 '22 19:09

Mihai Dinculescu