2012-08-16 57 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)