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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With