如何重置 ActiveRecord 迁移中的自动增量字段?
在我的迁移中,我有:
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 表中已有的数据
,但是即使我在 MySQL 上指定了 id
,它仍会从已有的位置继续编号。
我需要将计数器放在 id
的自动增量上,以便通过我的 Ruby on Rails 应用程序上的 Active Record 迁移只有这 3 个具有该 id 值的新记录。
In my migration I have:
def up
MyModel.destroy_all
MyModel.create!({:id=>1,:name=>'foo'})
MyModel.create!({:id=>2,:name=>'fooBar'})
MyModel.create!({:id=>3,:name=>'fooNull'})
end
because I need to override data that was already on my_models table
But Even though I'm specifying the id
on MySQL it continues the numbering from the position it already was.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您有 2 个单独的问题。一是你试图通过批量分配来指定 id,rails 不允许你这样做。有关执行此操作的方法,请参阅覆盖 ActiveRecord 中创建时的 id。
另一个问题是自动增量没有重置。每个 DBMS 都有一种独特的设置增量计数器的方法,并且 Rails 并没有为您提供访问它们的通用方法,尽管它是针对其中一些(不是 MySQL)实现的,请参阅 Rails 方式重置 id 字段上的种子
因此,您需要为此运行 MySQL 特定的 SQL,类似于:
这个应重置为表中最大 id 之后的数字(如果没有,则为 1)
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:
This should reset to the number after the largest id in your table (1 if there aren't any)
PostgreSQL:
例如,重置 User 模型的自动增量字段如下所示:
MySQL:
例如,重置 User 模型的自动增量字段如下所示:
PostgreSQL:
For example, resetting the auto increment field for the User model would look like:
MySQL:
For example, resetting the auto increment field for the User model would look like:
如果其他人想知道如何使用 MYSQL 执行此操作:这里是在迁移中使用的代码,以便重置表的自动增量:
foo_bars
是您的 auto_increment 的表名称正在重置。感谢这个问题的答案,我明白了这一点。
In case anyone else wonders how to do this with MYSQL: here is the code one would use in the migration in order to reset the auto increment for a table:
foo_bars
would be the table name whose auto_increment you are resetting.I figured this out thanks to the answer for this question.
对于 sqlite3 它将是:
for sqlite3 it would be: