【问题标题】:Rails 3 find_or_create by more than one attribute mongoidRails 3 find_or_create 由多个属性 mongoid
【发布时间】:2012-08-12 16:39:25
【问题描述】:

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

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

    它应该可以工作。

    【讨论】:

    • 我如何仅通过第一个属性找到,然后 - 仅在没有找到的情况下 - 使用其他属性创建?
    • @ChristofferJoergensen, Client.create_with(locked: false).find_or_create_by(first_name: 'Andy') 看看文档:guides.rubyonrails.org/active_record_querying.html
    【解决方案2】:

    来自querying 上的 mongoid 文档:

    Model.find_or_create_by

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

    【讨论】:

      【解决方案3】:

      克里斯托弗,

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

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

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

      【讨论】:

        猜你喜欢
        • 2014-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        相关资源
        最近更新 更多