0

I am printing id of the record in after save callback method as shown below. after printing the "id" i am raising the exception.

def after_save_run
  puts "id is #{self.id}"
  raise "exception"
end

Above method is generating below output for every save call

id is 1
id is 2
id is 3

Due to the exception in the after save method no records are saving in the database and hence my table is empty but then How acitverecord auto increments the primary key? How does activerecord knows what was the last generated id if there are no records in table?

user2274074
  • 991
  • 2
  • 9
  • 25
  • 2
    Does this answer your question? [serial in postgres is being increased even though I added on conflict do nothing](https://stackoverflow.com/questions/37204749/serial-in-postgres-is-being-increased-even-though-i-added-on-conflict-do-nothing) – Int'l Man Of Coding Mystery Mar 31 '20 at 15:37

1 Answers1

1

This is because internally, the ID isn't determined by Rails - it's given by a 'sequence' in your RDBMS. This sequence is a running counter that is incremented whenever you pull a new number out of it - whether or not you actually commit that number into your table.

This means that attempting insert a new row will increment the sequence counter, and since you're raising an exception that row isn't saved. But that does not change the fact that a number has been pulled out of the sequence and cannot be put back into it.

The sequences are also table agnostic for the most part - you could share the same sequence across tables if you wanted to.

https://www.postgresql.org/docs/current/functions-sequence.html

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90