Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear database before seeding in rails

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.

like image 212
Jesse Novotny Avatar asked Sep 22 '16 17:09

Jesse Novotny


People also ask

What does rake db drop do?

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.

How delete all data from table in rails?

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.


3 Answers

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.

like image 59
Vishal Nagda Avatar answered Oct 13 '22 23:10

Vishal Nagda


You can use this command

rake db:reset
like image 2
Deepak Mahakale Avatar answered Oct 14 '22 00:10

Deepak Mahakale


In my Rails 5 environment.

rails db:purge
rails db:migrate
rails db:seed

Or all together.

rails db:purge db:migrate db:seed
like image 2
Ian Purton Avatar answered Oct 14 '22 01:10

Ian Purton