13

I'd like the ID's of my Order model to start at 1000, and count up autoincrementally from there.

Can this be done via migration?

Jordan Warbelow-Feldstein
  • 10,510
  • 12
  • 48
  • 79

3 Answers3

25

In your migration, after table has been created, update the sequence with something like this:

create_table :products do |t|
  t.string  :name
  # other stuff
end

# for Postgres
execute "SELECT setval('products_id_seq', 1000)"

# and for mysql ...
execute "ALTER TABLE products AUTO_INCREMENT = 1000"
Vitor Arimitsu
  • 168
  • 2
  • 7
Serge Balyuk
  • 3,442
  • 1
  • 23
  • 23
0

This has not been tested and I am not sure what db you are using.

create_table(:order, :id => false) do |t|
   t.integer :id, :options => 'PRIMARY KEY', :default => 1000

or if you already have the table try this migration

def change
  execute "ALTER TABLE orders AUTO_INCREMENT = 1000"
end
Kyle C
  • 4,077
  • 2
  • 31
  • 34
0

In case if you just need to start the ID of a table from a custom number(lets say 1001).

And you are not sure about writing migration for the same, You can run the following in the rails console:

ActiveRecord::Base.connection.execute("SELECT setval('table_name_id_seq', 1000)"

Tested worked well for me. Hope that helped.

user681
  • 193
  • 1
  • 11