如何将其他列的值复制为rails迁移中新列的默认值?

moy*_*o20 10 migration activerecord ruby-on-rails

我有一个带有列的模型price.我需要添加一个new_column,marked_price其值为price默认值.我可以在迁移中写这个,或者最好的方法是什么?

就像是:

class AddMarkedPriceToMenuItems < ActiveRecord::Migration
  def change
    add_column :menu_items, :marked_price, :decimal, :default => :price
  end
end
Run Code Online (Sandbox Code Playgroud)

Mih*_*scu 14

不,数据库不允许您使用DEFAULT表列上的设置执行此操作.

但是你可以使用ActiveRecord回调来做到这一点

class MenuItem < ActiveRecord::Base
  before_create :set_market_price_default

  private

  def set_market_price_default
    self.market_price = self.price
  end
end
Run Code Online (Sandbox Code Playgroud)

至于迁移本身,您可以market_price手动更新

def change
  add_column :menu_items, :marked_price, :decimal

  reversible do |dir|
    dir.up { MenuItem.update_all('marked_price = price') }
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,您可能希望创建本地迁移模型的副本,以便将来不会失去同步.

  • @WizardofOgz你是对的.我已经更新了我的答案.谢谢. (2认同)
  • 在迁移中引用您的模型类是一种不好的做法,因为您的迁移可能会在您的模型类更改/删除后执行。 (2认同)