Home > Software design >  No error on updating deleted object in rails
No error on updating deleted object in rails

Time:09-10

Rails executing update on deleted records.

I have a web app on ruby on rails in which I created some users and after that I opened the rails console and assigned U1 to one of my user let say last user then assigned the same User to U2. Then I run U1.destroy which executes successfullyyou can check screenshot after that I updated the name of user through U2 and it returns me true you can check screenshot Although, user was destroyed from database when I checked it. My concern is rails should give me false as there was no object in database against that ID.

CodePudding user response:

If you want to double check that record exists before updating you can use reload

user.reload.update(name: "Some Name")

It will raise ActiveRecord::RecordNotFound if record with such id is absent

CodePudding user response:

UPDATE changes the values of the specified columns in all rows that satisfy the condition. https://www.postgresql.org/docs/current/sql-update.html

Rails doesn't return false or raise an exception because the UPDATE is still a valid query in the database, even if no rows match the condition. If you connect directly to your PostgreSQL database and run...

UPDATE users
SET name = 'test'
WHERE id = 123

...if 123 is an id that no longer exists, then the database will successfully execute the query and respond with:

UPDATE 0

If it is an id that still exists, the database will respond with:

UPDATE 1

This is similar to how Rails behaves if you use update_all. If you were to run update_all on a record that no longer exists, you'd see something like:

User.where(id: 123).update_all(name: 'test')
 => 0

But if the record exists you'd see:

User.where(id: 123).update_all(name: 'test')
 => 1

No error will be raised.

The purpose of the Rails update and update_all methods is just to attempt to run an UPDATE query in the database. If there is a timing issue and the record no longer exists, that's not something that the database or Rails is designed to give warnings about.

  • Related