How to reset auto increment field in a ActiveRecord migration?

后端 未结 3 2005
囚心锁ツ
囚心锁ツ 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:30

    You have 2 separate issues. One is that you are trying to specify the id with mass assignment, rails won't allow you to do that. See Overriding id on create in ActiveRecord for a way to do that.

    The other issue is that the auto-increment isn't resetting. Each DBMS has a unique way of setting an increment counter, and rails doesn't give you a generic way to access them, although it is implemented for some of them (not MySQL), see Rails way to reset seed on id field

    So you'll need to run the MySQL specific SQL for this, which is something like:

    ALTER TABLE my_models AUTO_INCREMENT = 1;
    

    This should reset to the number after the largest id in your table (1 if there aren't any)

提交回复
热议问题