I'd like to drop and setup my rails db while in runtime using ActiveRecord. What's the best way to do that? I'm assuming I need to drop the existing connection, and reconnect?
Does anyone have experience in doing this, and can you share what steps are involved to doing it properly?
I didn't have much luck with doing the typical drop, create, migrate in run-time, so I used the following approach (suggested by @David Aldridge):
connection ||= ActiveRecord::Base.connection
connection.tables.each do |t|
connection.execute("TRUNCATE \"#{t}\" RESTART IDENTITY CASCADE") unless t == 'schema_migrations'
end
I should first mention that I'm using postgres.
The problem I was running into previously was that I was getting blocked by index constraints in the db, but using the CASCADE
argument solved that.
CASCADE
allows for associated tables to also be truncated -- essentially bypassing constraints
RESTART IDENTITY
allows for resetting the table increment to zero.