2012-09-17 44 views
0

鑑於產生範圍的模型ID

class Account < ActiveRecord::Base 
    has_many :orders 
end 

我需要生成每個帳戶的唯一訂單號。每個賬戶可以有1000個訂單,但1000個訂單不能存在於同一個賬戶中。

@account1 = Account.first 
@account1.orders.create(:price => 1.20) # order 1000 auto generated, next will be 1001 

account1然後不能有兩個訂單與數字1000但其他帳戶可以。

我正在努力實現這個最好的方式。

回答

1

我想補充的驗證,例如以下添加到您的訂單模式:

validates :order_no, :uniqueness => { :scope => :account, :message => "Try again saving, a deadlock might have occurred!"} 

確保,這些ID實際上是獨一無二的,沒有發生死鎖。然後添加以下驗證:

before_validation :generate_and_set_uniq_order_no 

def generate_and_set_uniq_order_no 
    # insert Amit's solution here, or anything else (e.g. sorting/unifying/incrementing) 
end 

真正得到一個uniq的ID。

+0

接受作爲答案,因爲:範圍位對答案很重要。 –

1

使用Table Sequencing表中每個帳戶都有最後一個ID。您的表格的結構想要

ACCOUNT_ID CURRENT_ID 
3283 1000 
5078 1000 
9000  1 

每次創建訂單增量時,都將其用作訂單ID並更新該帳戶的CURRENT_ID。

注意與此解決方案的問題是Concurrency and Deadlock