I want to create a rake task in order to delete all records from a certain n
number of tables and reset the values of the id
column, so that when I create a new record it gets id 1.
Previous question Truncate table(s) with rails console is useful to get the job done for a single table (I would use delete_all
in place of destroy_all
if the task can be improved in performance):
Model.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY")
If I need to truncate more than one table, say tables table1
, table2
, table3
, is there any chance to use a single ActiveRecord connection such as:
Model1.delete_all
Model2.delete_all
Model3.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table1, table2, table3} RESTART IDENTITY")
and so avoid to establish multiple ActiveRecord connections like the example below?
Model1.delete_all
Model2.delete_all
Model3.delete_all
ActiveRecord::Base.connection.execute("TRUNCATE #{table1} RESTART IDENTITY")
ActiveRecord::Base.connection.execute("TRUNCATE #{table2} RESTART IDENTITY")
ActiveRecord::Base.connection.execute("TRUNCATE #{table3} RESTART IDENTITY")