For our new project it was necessary to modify the starting id of our database. This can be handled through migration for creating table but we decided to create a rake task that handled this for us.
The rake task that we created detects what database is being used and executes appropriate changes according to that.
You can create a rake task using rails generate command for rake task:
This will create your task in lib/tasks with chosen namespace and task name.
Here is our task and an explanation that follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
We need to change the starting id of our database to 1000 so we check that we don’t have a record with id higher than 1000. Link is our Active Record model and links is the name of our table.
ActiveRecord::Base.connection returns the connection currently associated with the class. We use it to detect the name of database and execute appropriate changes.
For MySQL we need to set AUTO_INCREMENT value to 1000, Auto-increment allows a unique number to be generated when a new record is inserted into a table. When first record is created it sets its primary key to 1 by default and it will auto increment by 1 for each new record.
For Postgres we have to explain what a sequence is. A sequence is a special kind of a database object designed for generating unique numeric identifiers. It is typically used to generate artificial primary keys. Sequences are similar to the Auto-increment concept in MySQL.
For SQlite we altered sqlite_sequence table, which is an internal table used to implement AUTOINCREMENT. It is created automatically whenever any ordinary table with an AUTOINCREMENT integer primary key is created.
You can check this Stack Overflow discussion that was very helpful to me.