ruby-on-rails – 如何将其他列的值复制为rails迁移中新列的默认
发布时间:2020-12-17 04:39:15 所属栏目:百科 来源:网络整理
导读:我有一个列价的模型.我需要添加一个new_column marked_price,其price值为默认值.我可以在迁移中写这个,或者最好的方法是什么? 就像是: class AddMarkedPriceToMenuItems ActiveRecord::Migration def change add_column :menu_items,:marked_price,:decima
我有一个列价的模型.我需要添加一个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,:decimal reversible do |dir| dir.up { MenuItem.update_all('marked_price = price') } end end 请注意,您可能希望创建本地迁移模型的副本,以便将来不会失去同步. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |