如何在迁移过程中处理自动递增主键
create table foo (id auto increment primary key, name varchar(255))
我编写了一个简单的 Rails 迁移脚本,该脚本在 self.up
上创建一条新记录,并使用 delete(:id => 1) 将其放到
。如果我执行 db:migrate ,它会创建一个 id=1 的新条目,如果我回滚,它将被删除。如果我在使用主键 id=2 创建记录时再次迁移/删除,并且我的删除脚本在回滚时失败,则会出现问题。self.drop
上
非常重要的是,主键每次都相同,因为我有基于此的其他依赖项。处理这个问题的正确方法应该是什么。
create table foo (id auto increment primary key, name varchar(255))
I wrote a simple rails migration script which creates a new record on self.up
and drops it on self.drop
with delete(:id => 1)
. If I perform db:migrate it creates a new entry with id=1 and if I rollback it gets removed. The problem occurs if I migrate / drop again as the record gets created with primary key id=2 and my drop script fails on a rollback.
It is very important that the primary key is the same every time as I have other dependencies based on that. What should be the right way to handle this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应使用迁移来添加种子数据,而应使用 db/seed.rb 文件。当您执行
rake db:reset
时,这将重新安装您的种子数据,这还将重置您的 id 计数器,以便数据将具有可预测的 id。执行rake db:reset
时,通过迁移添加的数据不会重新加载!You should not use migrations for adding seed data, use the
db/seed.rb
file instead. This will reinstall your seed data when you dorake db:reset
, this will also reset your id counters so the data will have predictable ids. Data added through migrations will not be reloaded when doing arake db:reset
!我认为处理它的正确方法是删除表而不是删除记录。当您在 self.up 方法中创建表时,您可以对其执行删除操作。
I think the right way to handle it is dropping the table instead of deleting records. As you create the table in your self.up method you can perform a drop on it.
执行此操作的是 MySQL 中的
AUTO_INCRMENT
选项。我认为 ActiveRecord 不允许您将其关闭。不过,您可以通过删除 MySQL 中 id 字段的AUTO_INCRMENT
值来关闭它(您必须为此执行 MySQL 查询)。再想一想,您正在数据库中维护一些孤立记录。我认为这不是正确的做法。尝试从 Rails 控制台中删除这些内容,并正确设置模型,以便在删除母记录时删除相关记录,然后使用一些 rake 脚本或其他内容再次添加数据并设置所需的关联。
The thing that does this is
AUTO_INCREMENT
option in MySQL. I dont thinkActiveRecord
allows you to turn it off. However you could turn it off by removingAUTO_INCREMENT
value for the id field in MySQL (you will have to execute a MySQL query for this.)On second thought, you are maintaining some Orphan records in your database. I dont believe this would be the right thing to do. Try deleting these things from the Rails console with models properly setup to delete dependent records when the mother record gets deleted and then use some rake scripts or something to add the data again and set up required associations.