如何在 Rails 中更改记录的主 ID? [英] How to change primary ID of a record in Rails?

查看:13
本文介绍了如何在 Rails 中更改记录的主 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<前>导轨控制台u = User.find(9)u.id = 7 # 没有其他id为7的记录保存=> 真用户名

id 没有改变.

如何更改主ID?为什么它会阻止此操作?

在 Rails 3.0.7 和 PostgreSQL 中工作.

既然有充分的理由不这样做,我会解释为什么,希望这是一个很好的理由.

我们正在对 Staging 进行可用性测试,所以我希望它看起来像生产环境,让每个人都可以轻松使用.我不想在可用性测试过程中造成混乱或错误,因为在 Staging 上有一些东西在一个 order 中,而在 Production 上有一个不同的 order.我在 Staging DB 上只更改了一个 PK id.

不要在您的生产数据库上执行此操作!

解决方案

我不确定为什么它会阻止该操作,但它确实阻止了它.

您可以为用户使用 update_all 方法绕过此问题.

User.where(id: 7).update_all(id: 9)

尽管可能的话,您确实应该避免这样做.

rails console
u = User.find(9)
u.id = 7 # There is no other record with id 7
u.save
=> true
User.all

The id has not changed.

How to change the primary ID? Why does it prevent this action?

Working in Rails 3.0.7 and PostgreSQL.

EDIT: Since there are good reasons not to do this, I'll explain why and hopefully it is a good reason.

We are doing Usability Testing on Staging, so I want it to look like the Production to make it easy for everyone. I don't want to create confusion or errors in the Usability Testing process by having some things in one order on Staging and in a different order on Production. I only changed one PK id on Staging DB.

Don't do this on your production DB!

解决方案

I'm not sure as to why it prevents that action, but it does for sure prevent it.

You can bypass this using the update_all method on for the user.

User.where(id: 7).update_all(id: 9)

Though if possible, you really should avoid doing this.

这篇关于如何在 Rails 中更改记录的主 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆