Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a join table in rails?

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?

like image 241
maček Avatar asked Sep 09 '10 02:09

maček


1 Answers

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.

like image 68
Nathan Long Avatar answered Oct 01 '22 13:10

Nathan Long