To truncate an ActiveRecord table, I can do
Category.destroy_all
or
Post.destroy_all
How does one go about truncating a categories_post table?
For a true TRUNCATE, you can use execute to run the raw SQL.
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name}")
Your examples using models weren't doing true TRUNCATE queries.
destroy_all does not TRUNCATE a table. It "destroys the records matching conditions by instantiating each record and calling its destroy method" (link).delete_all is closer - it ignores callbacks - but still not a TRUNCATE.Using the execute method deletes the rows from the database without creating any model instances.
Also, an actual TRUNCATE query, at least in MySQL, will reset the auto-increment on the primary key, so that the next record you insert will have id of 1.
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