3

Due to an error that deleted a user in our Rails app I'm trying to force another user record into the old records 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

What's going on here?

Meltemi
  • 37,979
  • 50
  • 195
  • 293

1 Answers1

5

Your update statement is constructed using the id of the in memory object, which you have set to 2. You can't update a record that doesn't exist.

If you want to stay in active record land I think you can do: User.update(5, id: 2)

Failing that, you can definitely do it in SQL. UPDATE users SET id = 2 WHERE id = 5.

Derek Prior
  • 3,497
  • 1
  • 25
  • 30
  • Can this be done across tables too, for relationships? For example you have the same company entered twice in the db, there are also relationships to both and you'd need all relationships to one to refer the other so you can merge them. – unom Feb 06 '17 at 14:59