GSt*_*Sto 5 migration ruby-on-rails-3
有没有办法在Rails 3.x中预先填充数据库表和迁移?我有一个状态列表,并且我希望能够在设置项目构建时预先填充它.
是的.创建表后,您可以调用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
Run Code Online (Sandbox Code Playgroud)
如果你想获得更多花哨,我会使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5219 次 |
| 最近记录: |