【发布时间】:2012-08-12 16:39:25
【问题描述】:
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid
如果你查看 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
您可以看到 find_or_create_by 接受 {} 作为第一个参数。你可以一次传入多个条件
something.find_or_create_by(name: 'john', age: 20)
它应该可以工作。
【讨论】:
来自querying 上的 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)
【讨论】: