Invoice Number with pessimistic locking (Rails)

# Shop class Shop < ActiveRecord::Base has_one :invoice_number end # InvoiceNumber class InvoiceNumber < ActiveRecord::Base belongs_to :shop def increment! transaction do lock! number = next_number self.next_number = number + 1 save! number end end end # CreateInvoiceNumbers class CreateInvoiceNumbers < ActiveRecord::Migration def change create_table :invoice_numbers do |t| t.belongs_to :shop, index: true, foreign_key: true t.integer :next_number, default: 1 end add_index :invoice_numbers, [:shop_id, :next_number], unique: true end end # Use case shop = Shop.find(1) invoice_number = shop.invoice_number || shop.create_invoice_number invoice_number.increment! # 1 invoice_number.increment! # 2

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.