10

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?

maček
  • 76,434
  • 37
  • 167
  • 198

2 Answers2

29

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.

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
0

I guess your join table is called categories_posts. CategoryPost.destroy_all should work, if not, maybe you need to specify the table name in the model (CategoryPost)

set_table_name "categories_posts"

Update, there isn't a CategoryPost model, so it should be created:

class CategoryPost < ActiveRecord::Base
  set_table_name "categories_posts"
end 
jordinl
  • 5,219
  • 1
  • 24
  • 20