Skip to content

Instantly share code, notes, and snippets.

@bergonom
Created March 15, 2013 22:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bergonom/5173714 to your computer and use it in GitHub Desktop.
Save bergonom/5173714 to your computer and use it in GitHub Desktop.
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