5

在这个链接Rails find_or_create by more than one attribute?可以将多个属性与活动记录一起使用。

如何在 mongoid 中使用多个属性?

谢谢

4

3 回答 3

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.

于 2012-08-16T11:19:05.620 回答
1

查询的 mongoid 文档中:

Model.find_or_create_by

通过提供的属性查找文档,如果没有找到,则创建并返回一个新持久的文档。

于 2012-08-16T11:12:04.267 回答
0

克里斯托弗,

我最近遇到了一个类似的问题,并在阅读了 mongoid git 存储库中的源代码后最终解决了这个问题:

在 mongoid 3.1.0 稳定分支中,这有效

    @new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value,
                                                        :attributeA => value,
                                                        :attributeB => value)
于 2014-02-21T04:37:15.200 回答