问题
Is there a rake command to wipe out the data in the database tables?
How do I create a db:seed script to pre-fill data to my tables?
回答1:
I use rake db:reset
which drops and then recreates the database and includes your seeds.rb file.
http://guides.rubyonrails.org/migrations.html#resetting-the-database
回答2:
You can delete everything and recreate database + seeds with both:
rake db:reset
: loads from schema.rbrake db:drop db:create db:migrate db:seed
: loads from migrations
Make sure you have no connections to db (rails server, sql client..) or the db won't drop.
schema.rb is a snapshot of the current state of your database generated by:
rake db:schema:dump
回答3:
If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all
(or delete_all
) in the seed.db file to clean out a table before your MyModel.create!(...)
statements load the data. Then, you can redo the db:seed
operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)
There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...
回答4:
As of Rails 5, the rake
commandline tool has been aliased as rails
so now
rails db:reset
instead of rake db:reset
will work just as well
回答5:
You can use rake db:reset
when you want to drop the local database and start fresh with data loaded from db/seeds.rb
. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.
Once the reset command is used it will do the following:
Drop the database: rake db:drop
Load the schema: rake db:schema:load
Seed the data: rake db:seed
But if you want to completely drop your database you can use rake db:drop
. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.
This is a detailed article about the most important rake database commands.
来源:https://stackoverflow.com/questions/4003978/reset-the-database-purge-all-then-seed-a-database