0

I'm developing an app in which users can create entries. Each entry needs a unique identifier. That identifier consists of 2 values:

  1. A user unique identifier code (ex: ZZ)
  2. The amount of entries the user has entered

So, if there's a user whose identifier is "ZZ", his entries will be identified by the following ids: "ZZ1", "ZZ2", "ZZ3" and so on.

Other users would have different identifier codes. And their entry count should be independent, even when they are all stored in the same table.

My first attempt was adding a "user_code" field in the users table, and the entry count was a scope in the model that counted the user entries. It does the job. But the problem arises when users delete their entries. The count gets messed up. Let's say that a user has 5 entries, but deletes the 4th entry. Then when a new he creates a new entry, it should be counted as the 6th entry. But since one entry was deleted, then the counter just counts 4 entries, instead of 5.

I'm looking for a better way to do this. Any ideas?

Thanks!

GuayoMena
  • 53
  • 1
  • 9

1 Answers1

0

Why not just use the standard rails id column? It will meet all of your requirements, increment itself, it won't go back when you delete an entry, and you don't have to write any code.

If you want the identifiers to be something other than a self incrementing integer, have a read of this thread.

Edit I misunderstood the question.

I would suggest adding the next_entry_id to the user model, then retrieving it in a before_create callback to set the value in the entry object and finally incrementing it in an after_create callback (in case db constraints fail the creation).

Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68
  • Entries for all users are inside the same table. The id column counts all entries. It's a global counter. I need to count entries from each individual user. – GuayoMena Feb 19 '16 at 13:59
  • Ah, why not store the `next_entry_id` in the user model, and have a callback on entry creation use then increment that value. – Matt Feb 19 '16 at 14:07