Rails 3 find_or_create with more than one mangoid attribute

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

How can I use more attribute in mongoid?

thank

+5
source share
3 answers

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 takes {}as the first argument. You can simply transfer several conditions at once.

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

and it should work.

+6
source

From mongoid docs to querying :

Model.find_or_create_by

, , .

+1

,

I recently ran into a similar problem and finally figured it out after reading the source in the mongoid git repository:

In the mongoid 3.1.0 stable branch, this works

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

All Articles