Rails在迁移时预先填充表

时间:2010-11-19 20:29:59

标签: ruby-on-rails-3 migration

有没有办法在Rails 3.x中预先填充数据库表并进行迁移?我有一个状态列表,我希望能够在设置项目构建时预先填充它。

2 个答案:

答案 0 :(得分:6)

答案 1 :(得分:5)

是的。创建表后,您可以调用State模型并开始填充表。

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 gem进行批量插入。如果要导入数百或数千条记录,这也是一种很好的方法。

  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