Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Truncate a single table across multiple db types. I made this a private method in my application controller (app/controllers/application_controller.rb). Adapted from: https://gist.github.com/tvdeyen/3246525
def truncate_table table_name
config = Rails.configuration.database_configuration
connection = ActiveRecord::Base.connection
connection.disable_referential_integrity do
next if connection.select_value("SELECT count(*) FROM #{table_name}") == 0
case config[Rails.env]["adapter"]
when "mysql", "mysql2", "postgresql"
connection.execute("TRUNCATE #{table_name}")
when "sqlite", "sqlite3"
connection.execute("DELETE FROM #{table_name}")
connection.execute("DELETE FROM sqlite_sequence where name='#{table_name}'")
end
connection.execute("VACUUM") if config[Rails.env]["adapter"] == "sqlite3"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment