Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 find_or_create by more than one attribute mongoid

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

like image 347
hyperrjas Avatar asked Aug 16 '12 10:08

hyperrjas


1 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 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.

like image 53
Shailen Tuli Avatar answered Nov 03 '22 06:11

Shailen Tuli