Search code examples
ruby-on-railsrubypostgresqldbmigrate

Build db:rake task from existing Database


I have a project that has had alot of editing to the postgresql database.

I am tring to find out is there a way to build a new db:rake file so i can rebuild the database on new server easily. Without manually editing the db:rake files.

thanks

Ruby 1.9.3
CentOS 6.4
Ruby on Rails 3
postgresql 9.3

Solution

  • For clarity, I am assuming you are referring to the migration files when you mention db:rake files.

    In Rails, you don't want to rebuild the database using migration files. They can quickly become outdated, referring to things that no longer exist, etc. Instead, it is best practice to recreate the database using your schema.rb file instead. This is touched on an answer I wrote a while back. In short, the schema.rb file represents your database table structure; a snapshot, if you will. Note that it does not contain data, only the table structure.

    In your scenario, in order to create, or ensure your schema.rb is up to date, you simply need to dump the schema, like so:

    rake db:schema:dump
    

    This regenerates the schema.rb file. Then, to rebuild the database from this file in another environment, simply reload the schema, like so:

    rake db:schema:load
    

    As stated above, the schema.rb does not contain any data from the tables, it merely represents the structure. If you want to preload the database with initial / default values, you will want to use the seed.rb file. Simply write your .create statements, and run it like so:

    rake db:seed