0

I am having a table named users where as usual all the ids are auto incremented. This is the migration:

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      ...............
      t.timestamps
    end
end

Now I got a new requirement where the user ids generated should start with 1000. I have seen some links like this one, but here I am using sqlite3 for development, mysql for production. How can I modify the table? Is it possible to do anything in the model side? Please help.

Community
  • 1
  • 1
vrajb55
  • 131
  • 11
  • 1
    The first thing you need to fix is to change your development database to `MySQL`. – Rajdeep Singh Sep 21 '16 at 09:39
  • Possible duplicate of [Rails Migration for ID Column to Start at 1,000 and Autoincrement Up From There?](http://stackoverflow.com/questions/12076741/rails-migration-for-id-column-to-start-at-1-000-and-autoincrement-up-from-there) – Deepak Mahakale Sep 21 '16 at 09:39

2 Answers2

1

@RSB is right that you should consider changing your development DB to MySQL as well for consistency, but if you want to keep your current setup then you could run this migration only in the production environment like so:

class ChangeStartingIdForUsers < ActiveRecord::Migration
  def self.up
    if Rails.env.production?
      execute "ALTER TABLE users AUTO_INCREMENT = 10000;"
    end
  end
end
omnikron
  • 2,211
  • 17
  • 30
  • Can I continue without drop, create and migrating the table? Actually there are around hundreds of users. I want to leave them and continue the newly registered users from 1000. Is it possible? – vrajb55 Sep 21 '16 at 12:09
  • 1
    The auto_increment attribute only affects new entries in the table - it won't change anything that already is there. The only stipulation is that the number you choose to start from must be higher than any of the existing ids, otherwise mysql will start from the highest id + 1. You can read more about it in the [mySQL documentation](http://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html). – omnikron Sep 21 '16 at 13:46
1

The first thing you need to fix is to change your development database to MySQL. Development and Production databases should always be of same type.

Secondly, you can add this to migration file to solve your actual issue.

execute "ALTER TABLE users AUTO_INCREMENT = 1000;"

Hope that helps!

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • Can I continue without drop, create and migrating the table? Actually there are around hundreds of users. I want to leave them and continue the newly registered users from 1000. Is it possible? – vrajb55 Sep 21 '16 at 12:09
  • Does any other table has `user_id` column in it? – Rajdeep Singh Sep 21 '16 at 15:23