優化迴圈 Query DB,如何提前確保 generated token unique

建立一筆訂單時,我們會給予一串 serial number,作為訂單唯一識別。我們會寫出如下的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# app/models/model_name.rb
class ModelName < ActiveRecord::Base
include Tokenable
end

# app/models/concerns/tokenable.rb
module Tokenable
extend ActiveSupport::Concern

included do
before_create :generate_token
end

protected

def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless self.class.exists?(token: random_token)
end
end
end

Query 是使用搜尋效益較高的 exists

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×