2012-08-16 8 views

Respuesta

6

Si nos fijamos en la fuente en 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 

se puede ver que find_or_create_by acepta una {} como primer argumento. Puede pasar en varias condiciones a la vez

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

y debería funcionar.

+0

¡Muchas gracias! – hyperrjas

+0

¿Cómo puedo encontrar solo el primer atributo y luego, solo en caso de que no se encuentre nada, crear con los otros atributos? – ChristofferJoergensen

+1

@ChristofferJoergensen, Client.create_with (locked: false) .find_or_create_by (first_name: 'Andy'), eche un vistazo a los documentos: http://guides.rubyonrails.org/active_record_querying.html – mkralla11

1

De los documentos MongoId en querying:

Model.find_or_create_by

encontrar un documento por los atributos proporcionados, y si no se encuentra crear y devolver una nueva persistido uno.

0

Christoffer,

me encontré con un problema similar hace poco y con el tiempo lo descubrí después de leer la fuente en el repositorio git MongoId:

En MongoId 3.1.0 rama estable, esto funciona

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