Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear whole database in Rails seeds.rb

What is the best way to accomplish this? As for now I'm using:

Role.delete_all User.delete_all ... 

but how to clear habtm talbes? Like roles_users

Updated Answer

I think ream88 response answers my question most precisely, but probably the bestidea is to follow coreyward suggestion to use separate rake tasks and leave seeds.rb only for seeding data.

This is updated answer from ream88 which doesn't delete schema_migrations table.

ActiveRecord::Base.establish_connection ActiveRecord::Base.connection.tables.each do |table|   # MySQL   ActiveRecord::Base.connection.execute("TRUNCATE #{table}") unless table == "schema_migrations"    # SQLite   # ActiveRecord::Base.connection.execute("DELETE FROM #{table}") unless table == "schema_migrations" end 

Thanks a lot for help!

like image 684
chodorowicz Avatar asked Aug 08 '11 16:08

chodorowicz


People also ask

What is seed RB in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.

What is a Seeds RB file for?

The Purpose of seed.rb file is very simple, it allows us to accept data in our (Model of) database through writing in a file using a syntax and after rake task it populated as we entered this data through a Form using controller, models.


1 Answers

First of all, I don't think it's a good idea to mix concerns like this. The seeds.rb file is intended to seed the database with data, not reset it. There is already a rake task for resetting a database (rake db:migrate:reset) that just runs rake db:drop db:create db:migrate. If you're wanting to seed a fresh database, you can just run rake db:reset db:seed.

like image 182
coreyward Avatar answered Oct 16 '22 03:10

coreyward