In questo collegamento Rails find_or_create by more than one attribute? è possibile utilizzare più di un attributo con record attivo.Rails 3 find_or_create da più di un attributo mongoid
Come posso utilizzare più di un attributo in mongoid?
Grazie
In questo collegamento Rails find_or_create by more than one attribute? è possibile utilizzare più di un attributo con record attivo.Rails 3 find_or_create da più di un attributo mongoid
Come posso utilizzare più di un attributo in mongoid?
Grazie
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.
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.
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)
Grazie mille! – hyperrjas
Come trovo solo dal primo attributo, e poi - solo nel caso in cui non venga trovato nulla - creare con gli altri attributi? – ChristofferJoergensen
@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