File into database migration


I am trying to figure out an approach to load in our initial data into our database.

I have written some load_data migrations which populate a lot of the stuff, how some of the database items are images etc and I am trying to figure out how to approach added them to the database

during a rake db:migrate

I am thinking if I store the files in a folder off the RAILS_ROOT I should be able to run code in the migration script to add them to the database. Does this sound like a valid approach?



Here’s one way of building initial data into a migration. I put the data into a subdirectory of db/migrate called ‘initial_data’ so it’s a bit more clear that it was relevant at a particular point in time. You could certainly get the data some other way that using YAML fixtures loaded by ActiveRecord, but that all depends on what format your data has now.


Rob Biedenharn

=== db/migrate/001_create_borogroves.rb

require ‘active_record/fixtures’

class CreateBorogroves < ActiveRecord::Migration

class Borogrove < ActiveRecord::Base

belongs_to :jabberwocky

acts_as_list :scope => :jabberwocky

serialize :toves


def self.up

create_table :borogroves do |t|

t.column :name, :string

t.column :description, :string

t.column :jabberwocky_id, :integer

t.column :position, :integer

t.column :toves, :text



say_with_time(“Load initial data from fixture”) do

directory = File.join(File.dirname(FILE), “initial_data”)

say “Fixture directory is: #{directory}”, true

Fixtures.create_fixtures(directory, Borogrove.table_name)



def self.down

drop_table :borogroves



=== db/migrate/initial_data/borogroves.yml

<% stanza = Jabberwocky.find_by_name(‘stanza’) %>

<% counter = 0 %>

stanza_<%= counter += 1 %>:

id: <%= counter %>

name: “Fred”

description: “short”

jabberwocky_id: <%= %>

position: <%= counter %>


gyre: “only when brillig”

gimble: occasionally

slithy: certainly

and so on…

Thanks for this, not exactly what I wanted to do but it set me off on the right path.

I didn’t know about yaml but once you suggested it I found this:

What I have found is that I can add binary data to the database and then export it out, and then re-import it later.