2011-12-03 19 views
29

मुझे मॉडल ऑब्जेक्ट में सभी संबंधित_to एसोसिएशन को सूचीबद्ध करने और उनके माध्यम से पुनरावृत्त करने की आवश्यकता है। क्या इसे करने का कोई तरीका है?क्या सभी संबंधित_तो एसोसिएशन सूचीबद्ध करने का कोई तरीका है?

उत्तर

30

आप कक्षा के reflections हैश का उपयोग करने के लिए इसका उपयोग कर सकते हैं। वहाँ और अधिक सरल तरीके हो सकते हैं, लेकिन यह काम करता है:

# say you have a class Thing 
class Thing < ActiveRecord::Base 
    belongs_to :foo 
    belongs_to :bar 
end 

# this would return a hash of all `belongs_to` reflections, in this case: 
# { :foo => (the Foo Reflection), :bar => (the Bar Reflection) } 
reflections = Thing.reflections.select do |association_name, reflection| 
    reflection.macro == :belongs_to 
end 

# And you could iterate over it, using the data in the reflection object, 
# or just the key. 
# 
# These should be equivalent: 
thing = Thing.first 
reflections.keys.map {|association_name| thing.send(association_name) } 
reflections.values.map {|reflection| thing.send(reflection.name) } 
16
Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact 
#=> ["Foo", "Bar"] 
निश्चित रूप से

, आप पास कर सकते हैं: has_many, या किसी अन्य संघों भी

+0

डॉप किया गया! अच्छा ....! –

34

आप प्रतिबिंब से reflect_on_all_associations विधि का उपयोग कर सकते के लिए उदाहरण:

Thing.reflect_on_all_associations(:belongs_to) 
संबंधित मुद्दे

 संबंधित मुद्दे