Created
March 15, 2013 22:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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