Rails:强制新记录的特定 id(或更改现有的 id)

Mel*_*emi 3 ruby-on-rails clearance ruby-on-rails-4

由于在我们的 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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

Der*_*ior 5

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

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

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