2015-08-21 55 views

回答

0

創建一個rake任務並將默認值分配給空列。你也可以在遷移中做同樣的事情。

您必須爲此添加遷移,因爲遷移只能運行一次。但是rake任務可以運行多次。不需要擔心你運行耙子任務或不運行。

你的移民應具備:

def migrate(direction) 
    super 
    Xyz.where(:price_currency => nil).each do |xyz| 
    xyz.update(:price_currency => "USD") if direction == :up 
end 

def change 
    add_column :xyzs, :price_currency, :sting, default: "USD", null: false 
end 
0

如果創建遷移來添加新的非空列,只需指定一個默認值,存在的所有記錄將隨後採用默認值

class AddNotNullColumn < ActiveRecord::Migration 
    def change 
    add_column :table_name, :column_name, :column_type, null: false, default: 'default_value' 
    end 
end 

這應該一口氣做到這一切

相關問題