[英]How to copy other column's value as default value for a new column in rails migration?
我有一個列price
的模型。 我需要添加一個NEW_COLUMN marked_price
具有價值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
請注意,您可能希望創建本地遷移模型的副本,以便將來不會失去同步。
這是一種通用的求解方式,無需編寫查詢,因為查詢會受到風險。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.