How to reset auto increment field in a ActiveRecord migration?

后端 未结 3 2008
囚心锁ツ
囚心锁ツ 2021-02-07 11:46

In my migration I have:

def up
   MyModel.destroy_all
   MyModel.create!({:id=>1,:name=>\'foo\'})
   MyModel.create!({:id=>2,:name=>\'fooBar\'})
   M         


        
3条回答
  •  名媛妹妹
    2021-02-07 12:21

    If you are using PostgreSQL you can simply do:

    ModelName.connection.execute('ALTER SEQUENCE model_name_id_seq RESTART WITH 1')
    

    For example, resetting the auto increment field for the User model would look like:

    User.connection.execute('ALTER SEQUENCE users_id_seq RESTART WITH 1')
    

提交回复
热议问题