I believe you are overthinking it. The id
column in rails (which all models possess by default) works the way you are thinking.
If you want a more human readable number as well, I would look at this gem (it has a ton of potential uses):
https://github.com/norman/friendly_id
Edit:
Looks like you might actually be looking for basically number of children of a parent. Logic looks like this:
- When a parent is created a
child_count
column is set to 0
- Whenever child is created for that parent, it increments the parent count, saves the result (this must be done atomically to avoid problems), which returns the current
child_count
- Set that
child_count
the childs parent_child_id
.
The key trickly bit is that #2 has to be done atomically to avoid problems. So lock the row, update the column, then unlock the row.
Code roughly looks like:
# In Child model
after_commit :add_parent_child_id
def add_parent_child_id
parent.with_lock do
new_child_count = parent.child_count + 1
parent.child_count = new_child_count
parent.save!
self.update!(parent_child_id: new_child_count)
end
end