5

In this link Rails find_or_create by more than one attribute? can use more that one attribute with active record.

How can I use more than attribute in mongoid?

Thank you

Community
  • 1
  • 1
hyperrjas
  • 10,666
  • 25
  • 99
  • 198

3 Answers3

6

If you look at the source 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

you can see that find_or_create_by accepts a {} as the first argument. You can just pass in several conditions at once

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

and it should work.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
  • How do I find by the first attribute only, and then - only in case that nothing is found - create with the other attributes? – Cjoerg Dec 23 '13 at 15:51
  • 1
    @ChristofferJoergensen, Client.create_with(locked: false).find_or_create_by(first_name: 'Andy') , take a look at the docs: http://guides.rubyonrails.org/active_record_querying.html – mkralla11 Mar 19 '14 at 18:41
1

From the mongoid docs on querying:

Model.find_or_create_by

Find a document by the provided attributes, and if not found create and return a newly persisted one.

HargrimmTheBleak
  • 2,147
  • 1
  • 19
  • 19
0

Christoffer,

I ran into a similar issue just recently and eventually figured it out after reading the source in the mongoid git repository:

In mongoid 3.1.0 stable branch, this works

    @new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value,
                                                        :attributeA => value,
                                                        :attributeB => value)
tobig77
  • 301
  • 2
  • 5