I have a rails3 application,use apache/passenger in production environment. I have CarryingBill model,it has a bill_no attribute,the bill_no is auto generate before create,I use Rails cache (FileStore) to cache the current bill_no,wh开发者_如何学JAVAen create a new CarryingBill Model, use Rails.cache.read('bill_no') to get the current bill_no value, then set the CarryingBill instance bill_no, and call Rails.cache.write('bill_no',current_bill_no + 1) ,and so on. But when multi user concurrent create the CarryingBill model,the generated bill_no is duplicated,how to solve this problem?
One clever way is to create a BillNo model and coorresponding table with just an id attribute. Each time you create a CarryingBill, create a new BillNo record and assign it's id to the CarryingBill. That way you're using your db's auto-generated id for that model as your unique id maker..
class CarryingBill
before_create :make_bill_no
def make_bill_no
bill = BillNo.create
self.bill_no = bill.id
end
end
精彩评论