Rails:强制新记录的特定 ID(或更改现有 ID)
Rails: force specific id for new record (or change id of existing)
由于在我们的 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
这是怎么回事?
您的更新语句是使用您已设置为 2 的内存对象的 ID 构造的。您无法更新不存在的记录。
如果你想留在活动记录领域,我想你可以这样做:User.update(5, id: 2)
否则,您绝对可以在 SQL 中完成。 UPDATE users SET id = 2 WHERE id = 5
.
由于在我们的 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
这是怎么回事?
您的更新语句是使用您已设置为 2 的内存对象的 ID 构造的。您无法更新不存在的记录。
如果你想留在活动记录领域,我想你可以这样做:User.update(5, id: 2)
否则,您绝对可以在 SQL 中完成。 UPDATE users SET id = 2 WHERE id = 5
.