Montag, 6. Oktober 2008

Loading Tables with Defauls Application Data in Migrations

1. Rake a migration to make the table
2. Make a new directory 'development_data' in app/db/migrate/
3. Make a YML file with the "tablename.yml" (check pural!) containing the default data for the table you need for the application (don't mix wiht test data)
4. Run rake db:migrate to create the tables and load them with the default data from the YML

==== Table Create Migration example

> ruby script/generate migration Certificates title:string description:text

==== YML example


certificate:
..id: 1
..title: "All About This Certificate"
..description: "Blah Blah."

..id: 2
..title: "All About This Certificate"
..description: "More Blah Blah."

==== Create Load Migration example

> ruby script/generate migration Certificates title:string description:text

==== Load Data example


class LoadCertificatesData <>
..def self.up
....down
....directory=File.join(File.dirname(__FILE__),"development_data")
....Fixtures.create_fixtures(directory,"certificates")
..end

..def self.down
....Certificate.delete(:all)
..end
end


==== Load Data example

This strategy might fail over time if you are adding and deleting existing colums in migrations, so you might have to end up doing all your load migrations after all the structural migrations have finished.

However, this might fail to if table relations ships are complex - so then you might have to fall back to an administration interface in the application where you build the tables from the YML file with your own programming.

Keine Kommentare: