簡體   English   中英

Rails 3 find_or_create由多個屬性mongoid組成

[英]Rails 3 find_or_create by more than one attribute mongoid

在這個鏈接中, Rails find_or_create由多個屬性組成? 可以使用多個具有活動記錄的屬性。

如何在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)

它應該工作。

從關於查詢的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM