3

由于在我们的 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

这里发生了什么?

4

1 回答 1

5

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

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

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

于 2015-04-23T12:58:44.520 回答