Rails: Alter migrations during early development p

2020-05-24 17:03发布

问题:

During the very early phases of development in a Rails app, I prefer to modify the migrations files directly to add new columns (fields) to my tables (models) instead of piling up migrations to alter fields and/or do minor changes.

Is that possible in Rails?

回答1:

Presumably the fact that you are doing it indicates that it's possible!



回答2:

I run the following commands to solve this problem. Save it in a script and you are ready to go! Of course, this presumes that losing the data is fine. Loading the fixtures is easy enough to add to this script in any case.

#!/bin/sh
rake db:drop
rake db:create
rake db:migrate --trace

PS: My friend who gave me this idea calls this script rake_dance :)



回答3:

Cleanest solution, driven from Vijay Dev's solution is to create a rake task:

namespace :db do
  desc "Drops, recreates and seeds the database."
  task :reload => [:drop, :create, :migrate, :seed] do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:seed'].invoke
  end
end


回答4:

db:reset does what Omar suggests.



回答5:

I recommend using fixtures when taking this approach (as it allows quickly recreating sample data for the application after dropping the database to recreate). Another option is http://datamapper.org/ (does not require migrations).



回答6:

Found out we can combine everything in one command:

rake db:drop db:create db:migrate db:seed

Using a shell aliase makes it a snap to redo all old migrations.