Is there a simple line of code I can include at the top of my seed file to clear out each table before inserting new seed data without running any rake commands to rollback tables or databases?
I was thinking something like:
[Foo, Bar].each{|class| class.destroy_all}
The point is I want to add new data where each new insertion starts from id: 1. What I want to avoid is deleting a table with 100 rows and when I add new data it's starting from 101.
An added nuance is that rake db:reset loads directly from your schema. rb file as opposed to running all the migrations files again. You data gets blown away in all cases.
During development, you might find yourself needing to delete everything from a specific database table to refresh your data. You could drop the whole database and bring it back up again with rake:db:drop, rake:db:setup , but that's slow and indiscriminate.
Updated Answer
You've to install (OR you can add gem 'database_cleaner'
to your Gemfile) a GEM called Database Cleaner which helps to clean your database without affecting your database schema._
To clean your database each time whenever you do rake db:seed
then paste
# updated
require 'database_cleaner'
DatabaseCleaner.clean_with(:truncation)
on the top of your seed file. It'll clear your database and start count from 1
again.
Disclaimer : This updated answer is tested, and working perfectly in my system.
===========================================================================
Previous Untested Answer
Ya you can do that but it's depends on which database you're using.
Below I'm giving solution for some popular DBs.
In MySQL, TRUNCATE table;
deletes all rows and resets the auto increment counter.
In PostgreSQL, it does not do this automatically. You can use TRUNCATE TABLE table RESTART IDENTITY;
.
In SQLite, there is no TRUNCATE statement, instead, it's
DELETE FROM table;
DELETE FROM sqlite_sequence WHERE name='table';
You can also try this
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
end
You can select any one of the solution & implement it to your seed file.
I hope this will help you... ;)
Disclaimer : I've share my knowledge for the purpose of your help, but this solution was didn't tested.
You can use this command
rake db:reset
In my Rails 5 environment.
rails db:purge
rails db:migrate
rails db:seed
Or all together.
rails db:purge db:migrate db:seed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With