In one of the project that we're working on, we change the ID of all documents to start from 1000001. To do this, we need to execute SQL statement directly using the execute method of ActiveRecord.
execute "ALTER TABLE documents AUTO_INCREMENT = 1000001
Problem with adding this only in migration is that when the db is dropped and recreated or when the application is live and we want to setup the production box, we often only run rake db:schema:load
and so the statement above is not executed as it is not recorded in db/schema.rb
.
Our solution is to override the rake task db:schema:load
to run the execute statement besides loading the schema from db/schema.rb
In lib/tasks/databases.rake
:
require 'active_record'
namespace :db do
namespace :schema do
desc 'Load a schema.rb file into the database'
task :load => [:load_config] do
c = ActiveRecord::Base.connection
c.execute "ALTER TABLE inspections AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE work_orders AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE quote_requests AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE quotes AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE contracts AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE orders AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE invoices AUTO_INCREMENT = 1000001"
c.execute "ALTER TABLE change_orders AUTO_INCREMENT = 1000001"
end
end
end
This will ensure that the ALTER TABLE
statement is executed when we run rake db:schema:load
.