0

Let me explain :

I followed the M. Hartl tutorial and I did just like him with migrations. So now, I have the followings files in my db/migrate directory (I spare you the timestamps):

create_users.rb

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end

add_index_to_users_email.rb

class AddIndexToUsersEmail < ActiveRecord::Migration
  def change
    add_index :users, :email, unique: true
  end
end

add_password_digest_to_users.rb

class AddPasswordDigestToUsers < ActiveRecord::Migration
  def change
    add_column :users, :password_digest, :string
  end
end

add_remember_token_to_users.rb

class AddRememberTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :remember_token, :string
    add_index :users, :remember_token
  end
end

add_admin_to_users.rb

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

Is it possible to mix everything into create_users.rb like following, and delete the others migration files without any damage to my app ?

create_users.rb

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password_digest
      t.string :remember_token
      t.boolean :admin, default: false

      t.timestamps
    end
    add_index :users, :email, unique: true
    add_index :users, :remember_token
  end
end
oldhomemovie
  • 14,621
  • 13
  • 64
  • 99
Flo Rahl
  • 1,044
  • 1
  • 16
  • 33

1 Answers1

1

Yes, it is possible. A straighforward strategy for that might be:

  1. In order to avoid data loss, make a database dumb (create a DB backup)
  2. Drop and recreate the database:

    rake db:drop db:create
    
  3. Have all migrations merged into a single file like you've shown

  4. Run:

    rake db:migrate
    
  5. Restore the DB backup

Though, this may become tricky if you already have the application deployed on production.

oldhomemovie
  • 14,621
  • 13
  • 64
  • 99
  • Sometimes useful if you delete schema.rb before rake db:migrate. Basically rake db:migrate is generate a nice new schema.rb. Especially if you modify your fields and database structure in your migrations files. – Zoltan May 23 '13 at 22:55