'How can I add a number column that tracks deletions?
Is there a gem or some database logic which I can use to add a number column to my database that tracks adds and deletes?
For example, GitHub has issues. An issue has a database ID. But it also has a number which is like a human readable identifier. If an issue is deleted, the number continues to increase. And repo A can have an issue with a number, and that doesn’t conflict with repo B.
Solution 1:[1]
Create a new table add a column to the Table like deleteCount. Everytime you call delete function or method. Just add a line that increments deleteCount like deleteCount++ to the success block. Same goes to the add method.
Solution 2:[2]
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_countcolumn 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_countthe childsparent_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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ummer Zaman |
| Solution 2 |
