如何在ActiveRecord的迁移重置自动增量字段? [英] How to reset auto increment field in a ActiveRecord migration?
问题描述
在我的移民,我有:
def up
MyModel.destroy_all
MyModel.create!({:id=>1,:name=>'foo'})
MyModel.create!({:id=>2,:name=>'fooBar'})
MyModel.create!({:id=>3,:name=>'fooNull'})
end
因为我需要重写,这是已经在my_models表中的数据。
because I need to override data that was already on my_models table
不过,即使我指定了 ID
关于MySQL继续编号从位置就已经是。
But Even though I'm specifying the id
on MySQL it continues the numbering from the position it already was.
我需要休息的自动递增的计数器 ID
来只有这3个新的与我的Ruby on Rails应用的ID值槽活动记录迁移记录。
I need to rest the counter on the auto increment for id
to have only this 3 new records with that id values trough Active Record migration on my Ruby on Rails application.
推荐答案
您有两个不同的问题。其中之一是,您要指定与质量分配的ID,导轨不会允许你这样做。查看创建的ActiveRecord 一种方式来做到这一点重写ID。
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.
另一个问题是,自动递增不复位。每个DBMS都有设置一个增量计数器的一种独特的方式,和轨道不给你访问他们一个通用的方式,但它是为一些人(而不是MySQL的)实现的,看到的导轨的方式来重设上id字段的种子
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
所以你需要运行这个MySQL的特定的SQL,这是一样的东西:
So you'll need to run the MySQL specific SQL for this, which is something like:
ALTER TABLE my_models AUTO_INCREMENT = 1;
这应该重置的数量在表中最大的ID后(1如果没有任何)
This should reset to the number after the largest id in your table (1 if there aren't any)
这篇关于如何在ActiveRecord的迁移重置自动增量字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!