免责声明:我是 Mongoid 和 Rails 的新手,所以我可能完全错了。
看着可修改.rb https://github.com/mongoid/mongoid/blob/7ac104ce42401602b829ebee939bb2f9944b8411/lib/mongoid/criterion/modifiable.rb and many.rb https://github.com/mongoid/mongoid/blob/165b4c6e1c2e53fe705c74444ea054ffa7602c72/lib/mongoid/relations/many.rb它似乎没有锁定任何资源。
在我看来,它只是执行“where().first”查询,然后如果没有返回任何内容,则执行“create”查询:
def find_or(method, attrs = {}, &block)
where(attrs).first || send(method, attrs, &block)
end
对于 find_or_create_by,“send”将调用“create_document”:
def create_document(method, attrs = nil, &block)
klass.__send__(method,
selector.reduce(attrs || {}) do |hash, (key, value)|
unless key.to_s =~ /\$/ || value.is_a?(Hash)
hash[key] = value
end
hash
end, &block)
end
结论:对我来说,这似乎是一种方便的方法,不要指望它是“线程安全的”。我希望有更多关于此方法的文档。