0

My application uses Postgresql.
I would need to remove all rows from a set of tables (table1 to table4) and restart the id with one command from a rb file.

In the Postgresql documentation I found that TRUNCATE with RESTART IDENTITY would do the job as follows:

TRUNCATE table1, table2, table3, table4 RESTART IDENTITY;

According to How to restart id counting on a table in PostgreSQL after deleting some previous data? at Stackoverflow, I can use the following command:

ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")

So putting together the two documentations, would it be correct to use the following command:

ActiveRecord::Base.connection.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY")

considering that in the API dock documentation the connection method is reported as deprecated or moved?.

Community
  • 1
  • 1
Asarluhi
  • 1,280
  • 3
  • 22
  • 43

1 Answers1

2

The recommended way nowadays is to use an ActiveRecord::Base.connection_pool.with_connection block.

ActiveRecord::Base.connection_pool.with_connection do |conn|
  conn.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY")
end
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70