“Loading data in migrations”
July 8, 2008
I found migrations to be very useful tool to maintain data structures in a rails project. It is clean, easy to understand and fast when it comes to recreate a database.
During develoment, I faced several times the same problem: “How to import static data into the database?” Of course, one can create fixture and load it. But sometimes one needs more powerful tool.
So, I tried to import the data in the migrations themselves. Since the data to import was huge (tens of MBs), I did try several methods and approaches. Here is the result.
Fixtures in Migrations
This is method that I found on the web in an article of Adam Christensen Loading Fixtures in a Migration.
It shows how to load the fixtures file into database.
require 'active_record/fixtures'<br /><br />class CreateCategories < ActiveRecord::Migration<br /> def self.up<br /> create_table :categories do |t|<br /> t.column :name, :string<br /> end<br /><br /> Fixtures.create_fixtures(’test/fixtures’, File.basename(”categories.yml”, ‘.*’))<br /> end<br /> def self.down<br /> drop_table :categories<br /> end<br />end<br /><br /><br />
Entry Filed under: loading data in migrations, rails, ruby on rails. Tags: loading data in migrations, rails, ruby on rails.
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed