Deleting all records in a database table

Ruby on-RailsRubyDatabaseRuby on-Rails-3

Ruby on-Rails Problem Overview


How do I delete all records in one of my database tables in a Ruby on Rails app?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

If you are looking for a way to it without SQL you should be able to use delete_all.

Post.delete_all

or with a criteria

Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

See here for more information.

The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

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)

Solution 5 - Ruby on-Rails

BlogPost.find_each(&:destroy)

Solution 6 - Ruby on-Rails

If your model is called BlogPost, it would be:

BlogPost.all.map(&:destroy)

Solution 7 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin MeltzerView Question on Stackoverflow
Solution 1 - Ruby on-RailsHakonBView Answer on Stackoverflow
Solution 2 - Ruby on-RailslebreezeView Answer on Stackoverflow
Solution 3 - Ruby on-RailsKensoDevView Answer on Stackoverflow
Solution 4 - Ruby on-RailsdfaulkenView Answer on Stackoverflow
Solution 5 - Ruby on-RailsPhilipView Answer on Stackoverflow
Solution 6 - Ruby on-RailsstefView Answer on Stackoverflow
Solution 7 - Ruby on-RailsSimon NinonView Answer on Stackoverflow