Dudo
Dudo

Reputation: 4169

Rails migrations cleanup / redo

So, say I have 10 models that have been evolving over the course of 100 migration files. Is there some sort of utility that could look my schema and build 10 'clean' migration files?

migration:

class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos do |t|
      t.belongs_to  :bar
      t.string :baz
      t.integer :qux, default: 0
    end

    add_index :foos, :bar_id
  end
end

schema:

ActiveRecord::Schema.define(:version => 20140610225017) do
  create_table "foos", :force => true do |t|
    t.integer  "bar_id"
    t.string   "baz"
    t.integer  "qux",         :default => 0
  end

  add_index "foos", ["bar_id"], :name => "index_foos_on_bar_id"
end

I just feel like... if it knows how to go from the migration to the schema, then vice versa would be easy. Does this sound stupid?

Upvotes: 1

Views: 986

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10099

I find you can delete your migrations after they have all been applied to all the databases, development through production. If you want to populate a new development or production database from scratch you can either (a) backup production and restore to the new database, or (b) load from the schema.rb file using rake db:schema:load.

If you really want the migrations for some documentation or clarity, create a new schema rails g migration schema2014. After the migration has been applied to production, delete all the old migrations files and copy schema.rb into the new migration.

Upvotes: 1

tirdadc
tirdadc

Reputation: 4713

If you don't care about the actual data and you're dealing with a new installation where you want to just create the DB structure using the schema.rb, you should use rake db:schema:load.

More details:

rake db:schema:load vs. migrations

Generate a migration file from schema.rb

Upvotes: 0

Related Questions