मान लीजिए कि मेरे पास निम्न वर्ग हैं
class SolarSystem < ActiveRecord::Base
has_many :planets
end
class Planet < ActiveRecord::Base
scope :life_supporting, where('distance_from_sun > ?', 5).order('diameter ASC')
end
Planetएक गुंजाइश है life_supportingऔर SolarSystem has_many :planets। मैं अपने has_many संबंध को परिभाषित करना चाहूंगा ताकि जब मैं solar_systemसभी संबद्ध लोगों से पूछूं planets, तो यह life_supportingगुंजाइश अपने आप लागू हो जाए। अनिवार्य रूप से, मैं चाहूंगा solar_system.planets == solar_system.planets.life_supporting।
आवश्यकताओं को
मैं नहीं बदलना चाहते हैं
scope :life_supportingमेंPlanetकरने के लिएdefault_scope where('distance_from_sun > ?', 5).order('diameter ASC')मैं भी जोड़ने के लिए नहीं होने से दोहराव को रोकने के लिए चाहते हैं
SolarSystemhas_many :planets, :conditions => ['distance_from_sun > ?', 5], :order => 'diameter ASC'
लक्ष्य
मुझे कुछ पसंद है
has_many :planets, :with_scope => :life_supporting
संपादित करें: काम के आसपास
जैसा कि @phoet ने कहा, हो सकता है कि ActiveRecord का उपयोग करके डिफ़ॉल्ट गुंजाइश हासिल करना संभव न हो। हालाँकि, मुझे दो संभावित काम मिल गए हैं। दोनों दोहराव को रोकते हैं। पहला, लंबे समय तक, स्पष्ट पठनीयता और पारदर्शिता बनाए रखता है, और दूसरा एक सहायक प्रकार विधि है जिसका आउटपुट स्पष्ट है।
class SolarSystem < ActiveRecord::Base
has_many :planets, :conditions => Planet.life_supporting.where_values,
:order => Planet.life_supporting.order_values
end
class Planet < ActiveRecord::Base
scope :life_supporting, where('distance_from_sun > ?', 5).order('diameter ASC')
end
एक अन्य समाधान जो बहुत अधिक क्लीनर है, बस निम्नलिखित विधि को इसमें जोड़ना है SolarSystem
def life_supporting_planets
planets.life_supporting
end
और solar_system.life_supporting_planetsजहाँ भी आप उपयोग करना चाहते हैं उसका उपयोग करने के लिए solar_system.planets।
न तो सवाल का जवाब देता है, इसलिए मैंने उन्हें यहां रखा क्योंकि काम के आसपास किसी और को इस स्थिति का सामना करना चाहिए।