Reputation: 1062
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
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!
Upvotes: 26
Views: 25969
Reputation: 12397
I definitely agree with @coreyward's answer, but if you really want to clear all tables inside your seeds.rb
file, this snippet will do the job:
ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.tables.each do |table|
next if table == 'schema_migrations'
# MySQL and PostgreSQL
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
# SQLite
# ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
end
Upvotes: 16
Reputation: 80070
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
.
Upvotes: 49
Reputation: 1082
You can try Rake::Task["db:reset"]
invoke.
rake db:reset is just a rake task you can call to reset the database, using Rake::Task lets you call it from a script.
Upvotes: 4