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