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?
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.
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