2012-08-16 13 views

Odpowiedz

6

Jeśli spojrzeć na źródła w/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 

widać, że find_or_create_by akceptuje {} jako pierwszy argument. Możesz po prostu przekazać kilka warunków jednocześnie:

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

i powinno działać.

+0

Dziękuję bardzo! – hyperrjas

+0

Jak znaleźć tylko pierwszy atrybut, a następnie - tylko w przypadku, gdy nic nie zostanie znalezione - utworzyć z innymi atrybutami? – ChristofferJoergensen

+1

@ChristofferJoergensen, Client.create_with (locked: false) .find_or_create_by (first_name: 'Andy'), spójrz na dokumenty: http://guides.rubyonrails.org/active_record_querying.html – mkralla11

1

od mongoid docs na querying:

Model.find_or_create_by

Znajdź dokument dostarczonych atrybutów, a jeśli nie znaleziono tworzyć i powrócić nowo utrzymywało jeden.

0

Christoffer,

wpadłem na podobnym problemie niedawno iw końcu zorientowaliśmy się po przeczytaniu źródło w mongoid repozytorium git:

W mongoid 3.1.0 stabilnej gałęzi, to działa

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