Rails: User specific sequential column

Posted by Alex Marchant on Stack Overflow See other posts from Stack Overflow or by Alex Marchant
Published on 2013-11-01T03:48:36Z Indexed on 2013/11/01 3:53 UTC
Read the original article Hit count: 86

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about ruby-on-rails