I have a Rails app where we generate calls. Each call has an incident_number which is a unique number based off the following format: 14-00001 (year in 2 digit followed by a dash then a 5 digit number).
The following code generates an incident number for the Call
record by getting the incident year, stripping it to two digits, checking if there are any call records and if the count is 0 then generate the first number as 00001 otherwise it pulls the last incident_number and increments by 1.
call.rb model
before_create :generate_incident_id
def generate_incident_id
incident_year = Time.now.year.to_s[2..-1]
if Call.count == 0
self.incident_number = "#{incident_year}-00001"
else
last_incident_number = Call.last.incident_number
number = last_incident_number.split('-')[1].to_i
number += 1
self.incident_number = incident_year + '-' + "%05d" % number
end
end
This code works fine and as designed but I'd like to refactor it somehow to do the following.
When the next year rolls around i.e 2015, the first part of the number is 15 but I'd like to reset the call incident_number
sequence so that the first call of the year is 15-00001 instead of 15-10233 (as an example). So far each time the new year rolls around I have to manually reset the incident number of the first call of the year to i.e. 14-00001. I'd like to find a way programmatically to check if the call is the first call of the new year and reset the incident_number to 15-00001.