2012-08-16 41 views

回答

6

如果你看一下的lib/mongoid/finders.rb来源:

# Find the first +Document+ given the conditions, or creates a 
# with the conditions that were supplied. 
    ... 
# @param [ Hash ] attrs The attributes to check. 
# 
# @return [ Document ] A matching or newly created document. 
def find_or_create_by(attrs = {}, &block) 
    find_or(:create, attrs, &block) 
end 

你可以看到,find_or_create_by接受{}作为第一个参数。你可以一次通过几个条件

something.find_or_create_by(name: 'john', age: 20) 

它应该工作。

+0

非常感谢! – hyperrjas 2012-08-16 13:19:49

+0

如何仅通过第一个属性查找,然后 - 仅在没有发现任何内容的情况下 - 使用其他属性创建? – ChristofferJoergensen 2013-12-23 15:51:03

+1

@ChristofferJoergensen,Client.create_with(locked:false).find_or_create_by(first_name:'Andy'),看看文档:http://guides.rubyonrails.org/active_record_querying.html – mkralla11 2014-03-19 18:41:40

1

从mongoid文档上querying

Model.find_or_create_by

通过所提供的属性查找文件,如果没有找到创建 并返回一个新坚持一个。

0

克里斯托弗,

我刚刚碰到了类似的问题,并最终在mongoid git仓库阅读源后想通了:

在mongoid 3.1.0稳定分支,这个工程

@new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value, 
                 :attributeA => value, 
                 :attributeB => value)