Topic: Race condition unbreakable generating next order number

I have simple order model and i need to generate order numbers (10000, 10001, ...) and i have  all orders from many stores in one table so i cannot rely on sequence auto increments in database.

Proof of concept is something like:

  before_validation_on_create :generate_no


  def generate_no
    last = Order.find(:first, :conditions => ["store_id = ?", self.store.id], :order => 'created_on DESC')
    if last.nil? then
      self.no = 10_000
    else
      self.no = last.no.to_i + 1 # increment No
    end
  end


But of course it is easily brekable by two concurent requests, any ideas how to make it race condition free?

Re: Race condition unbreakable generating next order number

Look into pessimistic locking. This will allow you to lock the table so rows can't be added while you are determining the proper number.

Railscasts - Free Ruby on Rails Screencasts

Re: Race condition unbreakable generating next order number

UPDATE: I have final solution

In controller:
[code=]def place_order
    @title = 'Objedn

Last edited by daeltar (2007-04-10 15:50:17)