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 successfully
after that I updated the name of user through U2 and it returns me true 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.
2
Answers
Rails doesn’t return
false
or raise an exception because theUPDATE
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……if
123
is anid
that no longer exists, then the database will successfully execute the query and respond with:If it is an
id
that still exists, the database will respond with:This is similar to how Rails behaves if you use
update_all
. If you were to runupdate_all
on a record that no longer exists, you’d see something like:But if the record exists you’d see:
No error will be raised.
The purpose of the Rails
update
andupdate_all
methods is just to attempt to run anUPDATE
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.If you want to double check that record exists before updating you can use
reload
It will raise
ActiveRecord::RecordNotFound
if record with suchid
is absent