在我的邀请.rb 模型中,我有以下内容:
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
有任何想法吗?谢谢