Change starting id number

前端 未结 6 912
灰色年华
灰色年华 2021-02-05 10:53

I have an \'Account\' model in Rails with its corresponding \'accounts\' table in the database. If I wipe the database and start over, the \'account_id\' field will always star

6条回答
  •  无人及你
    2021-02-05 11:37

    in SQL Server:

    execute('DBCC CHECKIDENT (accounts, reseed, 1000)')
    

    In my case, the development environment and the production environment are using different type of database.

    This code block will run the relevant execution accordin to DB type - just put it in the relevant migration:

    puts 'Migration trys to set initial account ID to adapter:' + ActiveRecord::Base.connection.adapter_name
    case ActiveRecord::Base.connection.adapter_name
      when 'MySQL'
        execute('ALTER TABLE accounts AUTO_INCREMENT = 1000')
      when 'SQLServer'
        execute('DBCC CHECKIDENT (accounts, reseed, 1000)')
      when 'SQLite'
        begin
          execute('insert into sqlite_sequence(name,seq) values(\'accounts\', 1000);')
        rescue
          puts 'insert error... updating'
        end
        execute('update sqlite_sequence set seq = 1000 where name = \'accounts\';')
      else
        puts "cant recognize the database"
    end
    

提交回复
热议问题