在我invite.rb模型我有以下幾點:爲什麼validates_uniqueness_of在before_create之前運行?
class Invite < ActiveRecord::Base
before_create :assign_code
validates_uniqueness_of :code, :case_sensitive => false, :message => "This invite code is taken!"
protected
# Create a safe random token and ensuring it's uniqueness for the model
def assign_code
begin
code = SecureRandom.urlsafe_base64
end while Invite.where(:code => code).exists?
self.code = code
end
問題是我看到下面的跟蹤日誌。爲什麼rails對空值的代碼進行查詢,看起來像是浪費的查詢。
Invite Exists (0.5ms) SELECT 1 AS one FROM "invites" WHERE "invites"."code" IS NULL LIMIT 1
Invite Exists (0.3ms) SELECT 1 AS one FROM "invites" WHERE "invites"."code" = 'mTGCX0yCyTgplGfGQ5hGeA' LIMIT 1
任何想法?謝謝