2010-11-19 75 views
4

有沒有辦法在Rails 3.x中預填充數據庫表中的遷移?我有一個狀態列表,我希望能夠在我設置項目的構建時預先填充它。Rails在遷移中預填充表

回答

4

是的。創建表後,您可以調用狀態模型並開始填充表。

class LoadStates < ActiveRecord::Migration 
    def self.up 
    states = ['state1','state2','state2'] 
    for state in states 
     State.create(:name=>state) 
    end 
    end 

    def self.down 
    State.delete_all 
    end 
end 

如果你想獲得更看中我會用activerecord-import寶石做批量插入。如果您有數百或數千條記錄要導入,這也是一種很好的方法。

def self.up 
    states = ['state1','state2','state2'] 
    states_for_import = [] 
    for state in states 
     states_for_import << State.new(:name=>state) 
    end 
    State.import states_for_import 
    end 
+1

'在y'語法X? – fotanus 2014-02-17 20:57:10