我有一个带有列price
的模型。我需要添加一个值为marked_price
的new_column price
作为默认值。我可以在迁移中写这个吗,或者做这件事的最好方法是什么?
就像是:
class AddMarkedPriceToMenuItems < ActiveRecord::Migration
def change
add_column :menu_items, :marked_price, :decimal, :default => :price
end
end
最佳答案
不可以,数据库不允许您使用表列上的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
至于迁移本身,您可以手动更新
market_price
def change
add_column :menu_items, :marked_price, :decimal
reversible do |dir|
dir.up { MenuItem.update_all('marked_price = price') }
end
end
请注意,您可能想要创建模型的副本,该副本位于迁移过程中的本地位置,以免将来出现不同步的情况。
关于ruby-on-rails - 如何在Rails迁移中将其他列的值复制为新列的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743231/