2012-08-16 12 views
5

इस लिंक में Rails find_or_create by more than one attribute? सक्रिय रिकॉर्ड के साथ एक विशेषता का अधिक उपयोग कर सकते हैं।रेल 3 एक से अधिक गुणों द्वारा find_or_create mongoid

मैं mongoid में विशेषता से अधिक का उपयोग कैसे कर सकता हूं?

querying पर धन्यवाद

उत्तर

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) 

पर कई स्थितियों में बस पास कर सकते हैं और इसे काम करना चाहिए।

+0

बहुत बहुत धन्यवाद! – hyperrjas

+0

मैं केवल पहली विशेषता से कैसे पा सकता हूं, और फिर - केवल कुछ भी नहीं मिला है - अन्य विशेषताओं के साथ बनाएँ? – ChristofferJoergensen

+1

@CristofferJoergensen, Client.create_with (लॉक: झूठा) .find_or_create_by (first_name: 'एंडी'), दस्तावेज़ों पर एक नज़र डालें: http://guides.rubyonrails.org/active_record_querying.html – mkralla11

1

mongoid डॉक्स से:

Model.find_or_create_by

प्रदान की विशेषताओं के आधार पर एक दस्तावेज खोजें, और बना सकते हैं और एक नए कायम एक वापसी अगर नहीं मिला।

0

क्रिस्टोफ़र,

मैं अभी हाल ही में एक ऐसी ही मुद्दे में भाग गया और अंत में mongoid Git भंडार में स्रोत को पढ़ने के बाद यह पता लगा:

mongoid 3.1.0 स्थिर शाखा में, यह काम करता है

@new_object = NewObject.find_or_create_by(indexed_attribute: my_unique_value, 
                 :attributeA => value, 
                 :attributeB => value) 
संबंधित मुद्दे