Rails pre-populates table during migration

Is there a way to pre-populate a database table with migration in Rails 3.x? I have a list of states, and I would like to be able to pre-populate it whenever I set up the project assembly.

+4
source share
2 answers

Yeah. After creating the table, you can call up the state model and start filling out the table.

 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 

If you want more imagination, I would use an activerecord-import gem to do a volume insert. This is also a good approach if you have hundreds or thousands of records to 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 
+4
source

All Articles