Rails: User specific sequential column
- by Alex Marchant
I have an inventory system, where a User has many inventory. We have a barcode column which needs to be sequential for each user. I run into a problem however when doing bulk association building. I end up getting several inventories for a user with the same barcode.
For example:
Inventory Table:
id | user_id | barcode
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 2
5 | 1 | 3
In the Inventory model I have
before_validation :assign_barcode, on: :create
def assign_barcode
self.barcode = (user.inventories.order(barcode: :desc).first.try(:barcode) || 0) + 1
end
It generally works, but ran into a problem when seeding my db:
(1..5).each do
user.inventories.build(...)
end
user.save
I end up with a bunch of inventories for user that have the same barcode. How can I ensure that inventories have unique barcodes even when adding inventories in bulk?