Reputation: 570
How do I generate a unique sequential ID (that follows a pattern), each time a record is created? How do I address concurrency issues?
I want this ID to follow a fixed pattern. e.g.: ABC00001, ABC00002, ABC00003, etc
I am doing this to generate student IDs, and I want student IDs within an institute to to be sequential. There will be multiple institutes using my tool.
Upvotes: 2
Views: 1939
Reputation: 2321
If you're using active record then a unique sequential id (id
) is already created by default and takes care of all concurrency issues for you. If you need to use it for queries then a separate column might be the way forward, but if you just need to display it in a certain format you could simply define a method on your model like:
class MyModel
def my_unique_id
"ABC%.5d" % id
end
end
test = MyModel.create
test.id #=> 1
test.my_unique_id #=> "ABC00001"
test2 = MyModel.create
test2.id #=> 2
test2.my_unique_id #=> "ABC00002"
EDIT
Ah, you didn't mention that you needed the identifiers to be sequential within an Institute
. Are you using PostgreSQL? If so the sequenced gem might be a good bet – it adds an acts_as_sequence
method which allows you to do this:
class Student
acts_as_sequenced scope: :institute_id, column: :sequential_id
#...
end
If you are not using PostgreSQL you'd need to find a way of dealing with concurrency locks in your database system of choice, as the gem only caters for postgres (see here for how).
Upvotes: 6