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!
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.
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.
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
.
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