-1

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.

  • 1
    What you want sounds basically just like an ordinal column. On postgres you could do it with [a sequence](https://www.postgresql.org/docs/current/sql-createsequence.html) - on other DBs you have to create a separate table to accomplish the same thing. https://stackoverflow.com/questions/26578313/how-do-i-create-a-sequence-in-mysql – max May 07 '22 at 23:14
  • @max this is a great answer and I’d love to give you credit for it if you make it a reply. – RobertoSantio May 08 '22 at 18:26

2 Answers2

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.

Ummer Zaman
  • 336
  • 3
  • 4
0

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:

  1. When a parent is created a child_count column is set to 0
  2. 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
  3. 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 

Nuclearman
  • 5,029
  • 1
  • 19
  • 35