Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all records in a database table

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

like image 316
Justin Meltzer Avatar asked Mar 16 '11 07:03

Justin Meltzer


People also ask

What term means deleting all records from a table?

SQL Truncate is a data definition language (DDL) command. It removes all rows in a table.


2 Answers

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.

like image 149
HakonB Avatar answered Oct 01 '22 16:10

HakonB


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

like image 42
lebreeze Avatar answered Oct 01 '22 17:10

lebreeze