Rails 3 find_or_create由多个属性mongoid组成

时间:2012-08-16 10:33:30

标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid

在此链接中Rails find_or_create by more than one attribute?可以使用多个具有有效记录的属性。

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

谢谢

3 个答案:

答案 0 :(得分:6)

如果查看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)

它应该有用。

答案 1 :(得分:1)

来自querying上的mongoid文档:

  

Model.find_or_create_by

     

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

答案 2 :(得分:0)

克里斯托弗,

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

在mongoid 3.1.0稳定分支中,这可行

    @new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value,
                                                        :attributeA => value,
                                                        :attributeB => value)
相关问题