有没有办法在Rails 3.x中预先填充数据库表并进行迁移?我有一个状态列表,我希望能够在设置项目构建时预先填充它。
答案 0 :(得分:6)
您可以使用db/seeds.rb
。在新应用程序中填充表格的好方法。
http://ryandaigle.com/articles/2009/5/13/what-s-new-in-edge-rails-database-seeding
http://www.robbyonrails.com/articles/2009/09/05/planting-the-seeds
答案 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