I have a model object in my Rails application, let's call it Picture.
The pictures table in database has a primary key column called id
because Rails create them automatically according to convention, this column is just 1, 2, 3, 4.....
But I need another column called custom_id
to record its custom ID, I want its value to be
PIC2015-0001
,PIC2015-0002
,PIC2015-0003
for year 2015PIC2018-0001
,PIC2018-0002
,PIC2018-0003
for year 2018- and so on.
Basically PICYYYY-NUM_FOR_YEAR
, where YYYY
is the year it is created, and NUM_FOR_YEAR
is the number this record is created (first record created in a year will have 0001, second will have 0002, and so on... This number will restart for new record each new year)
I want to implement this by using the after_create hook and look up its created_at time stamp to get the year YYYY
, and infer the NUM_FOR_YEAR
by looking at last Picture with non-empty custom_id
. But I'm worried about synchronisation issue. What if the below happen (or will it happen at all?):
The below events happen in the time order listed
- Picture 1 created, after_create called and finished
- Picture 2 created
- Picture 3 created
- Picture 2 after_create called - fetch Picture 1's custom_id
- Picture 3 after_create called - fetch Picture 1's custom_id
- Picture 2 after_created finished
- Picture 3 after_created finished - this will have duplicate ID, which is wrong
What is the simplest way to solve this problem?