How do I delete all records in one of my database tables in a Ruby on Rails app?
This question is related to
ruby-on-rails
ruby
database
ruby-on-rails-3
BlogPost.find_each(&:destroy)
If you mean delete every instance of all models, I would use
ActiveRecord::Base.connection.tables.map(&:classify)
.map{|name| name.constantize if Object.const_defined?(name)}
.compact.each(&:delete_all)
More recent answer in the case you want to delete every entries in every tables:
def reset
Rails.application.eager_load!
ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration }
end
More information about the eager_load
here.
After calling it, we can access to all of the descendants of ActiveRecord::Base
and we can apply a delete_all
on all the models.
Note that we make sure not to clear the SchemaMigration table.
If your model is called BlogPost, it would be:
BlogPost.all.map(&:destroy)
To delete via SQL
Item.delete_all # accepts optional conditions
To delete by calling each model's destroy method (expensive but ensures callbacks are called)
Item.destroy_all # accepts optional conditions
All here
if you want to completely empty the database and not just delete a model or models attached to it you can do:
rake db:purge
you can also do it on the test database
rake db:test:purge
Source: Stackoverflow.com