2012-08-16 10 views

risposta

6

Se si guarda alla fonte in 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 

si può vedere che find_or_create_by accetta un {} come primo argomento. Puoi passare in diverse condizioni contemporaneamente

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

e dovrebbe funzionare.

+0

Grazie mille! – hyperrjas

+0

Come trovo solo dal primo attributo, e poi - solo nel caso in cui non venga trovato nulla - creare con gli altri attributi? – ChristofferJoergensen

+1

@ChristofferJoergensen, Client.create_with (locked: false) .find_or_create_by (first_name: 'Andy'), dai un'occhiata ai documenti: http://guides.rubyonrails.org/active_record_querying.html – mkralla11

1

Dalla documentazione mongoid su querying:

Model.find_or_create_by

trovare un documento dagli attributi previsti, e se non lo trova creare e restituire una nuova persisteva uno.

0

Christoffer,

mi sono imbattuto in un problema simile da poco e alla fine capito dopo aver letto la fonte nel repository git mongoid:

In mongoid 3.1.0 ramo stabile, questo funziona

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