Home > Back-end >  How does Ruby on Rails (or ActiveRecord) remember ID's when changing an ID?
How does Ruby on Rails (or ActiveRecord) remember ID's when changing an ID?

Time:01-24

First, I would like to state, I know it is bad practice to change an ID once it is set. However, I had a student ask: If you updated the ID of an existing record, would rails create a new row and leave the original row untouched, or change the ID of the existing row?

I figured we'd give it a shot and see what happened.

I changed the ID on the instance of the model, and then ran .save on the instance. Rails updated the original record and the SQL that was shown showed rails using the old ID in the WHERE clause, and the new ID in the actual update portion.

Where/How does Rails keep the old ID?

CodePudding user response:

it's not remembered. you have it until the update, in the id attribute in the database (or another one if you choose another field as a primary key), and then it's gone (unless you have something more sophisticated that logs every change).

CodePudding user response:

Let's we have some user with id 10 and try to change it:

user.id = 15

Rails track it with ActiveModel::Dirty methods:

user.changed?       # => true
user.id_changed?    # => true
user.id_was         # => 10
user.id_change      # => [10, 15]

If we call user.save and all validations will pass, SQL query will be executed like this:

UPDATE users SET id = 15 WHERE id = 10;

It will be UPDATE, not INSERT because rails know that it is existing record

Of course this will work for any columns, not only for id

  • Related