Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails pre-populate table in migration

Is there a way to pre-populate a database table w/ a migration in Rails 3.x? I have a list of states, and I'd like to be able to pre-populate it whenever I'm setting up a build of the project.

like image 528
GSto Avatar asked Nov 19 '10 20:11

GSto


2 Answers

You could use db/seeds.rb for this. Good way to populate tables in a fresh app.

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

like image 200
johnmcaliley Avatar answered Jan 04 '23 12:01

johnmcaliley


Yep. After you create the table you can invoke the State model and begin populating 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 wanted to get more fancy I'd use the activerecord-import gem to do a bulk 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
like image 22
rwilliams Avatar answered Jan 04 '23 11:01

rwilliams