【问题标题】:Rails: force specific id for new record (or change id of existing)Rails:强制新记录的特定ID(或更改现有的ID)
【发布时间】:2015-04-22 23:05:46
【问题描述】:

由于在我们的 Rails 应用程序中删除用户的错误,我正试图将另一个用户记录强制使用旧记录 ID。

$ rails console
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> replacer = User.find(5)
=> #<User id: 5, created_at: [omitted for brevity ...] >
replacer.id = 2
=> 2
replacer.save
=> true
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> User.find(5)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=5
> replacer
=> #<User id: 2, created_at: [omitted for brevity ...] >
> replacer.valid?
=> true

这里发生了什么?

【问题讨论】:

  • 你不能在 AR 上做,直接在数据库里做。
  • 我以前用 AR 做过类似的事情。不知道如何在数据库中执行此操作……奇怪的是记录似乎已保存但在 id:5 id:2 处找不到。就像它迷失在了边缘……
  • 当你replacer.save! 时会发生什么?

标签: ruby-on-rails ruby-on-rails-4 clearance


【解决方案1】:

您的更新语句是使用您已设置为 2 的内存对象的 id 构造的。您无法更新不存在的记录。

如果你想留在活跃的记录领域,我认为你可以这样做:User.update(5, id: 2)

如果做不到这一点,您绝对可以在 SQL 中做到这一点。 UPDATE users SET id = 2 WHERE id = 5.

【讨论】:

  • 对于关系,这也可以跨表完成吗?例如,您在数据库中输入了同一家公司两次,两者之间也存在关系,您需要与一个公司的所有关系来引用另一个公司,以便您可以合并它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多