在这个链接Rails find_or_create by more than one attribute?可以将多个属性与活动记录一起使用。
如何在 mongoid 中使用多个属性?
谢谢
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.
从查询的 mongoid 文档中:
Model.find_or_create_by
通过提供的属性查找文档,如果没有找到,则创建并返回一个新持久的文档。
克里斯托弗,
我最近遇到了一个类似的问题,并在阅读了 mongoid git 存储库中的源代码后最终解决了这个问题:
在 mongoid 3.1.0 稳定分支中,这有效
@new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value,
:attributeA => value,
:attributeB => value)