में एकाधिक सेल्फ-जॉइन के साथ कई से अधिक सहयोग मैं स्वयं-जुड़ने के माध्यम से उसी मॉडल के रिकॉर्ड के बीच कई संबंधों को लागू करने की कोशिश कर रहा हूं (@Shtééf's answer पर आधारित)। मेरे पास निम्नलिखित मॉडल हैंActiveRecord
create_table :relations, force: true do |t|
t.references :employee_a
t.string :rel_type
t.references :employee_b
end
class Relation < ActiveRecord::Base
belongs_to :employee_a, :class_name => 'Employee'
belongs_to :employee_b, :class_name => 'Employee'
end
class Employee < ActiveRecord::Base
has_many :relations, foreign_key: 'employee_a_id'
has_many :reverse_relations, class_name: 'Relation', foreign_key: 'employee_b_id'
has_many :subordinates, through: :relations, source: 'employee_b', conditions: {'relations.rel_type' => 'manager of'}
has_many :managers, through: :reverse_relations, source: 'employee_a', conditions: {'relations.rel_type' => 'manager of'}
end
इस सेटअप के साथ मैं प्रत्येक रिकॉर्ड के लिए अधीनस्थों और प्रबंधकों की सूचियों को सफलतापूर्वक एक्सेस कर सकता हूं। हालांकि, मैं निम्नलिखित तरीके
e = Employee.create
e.subordinates.create
e.subordinates #=> []
e.managers.create
e.managers #=> []
समस्या यह संबंधों के प्रकार निर्धारित नहीं करता है वह यह है कि में संबंध बनाने के लिए आती है, तो मैं लिखने के लिए
e = Employee.create
s = Employee.create
e.relations.create employee_b: s, rel_type: 'manager of'
e.subordinates #=> [#<Employee id:...>]
मैं कुछ गलत कर रहा हूँ है?
और मैं पूरी तरह से निश्चित नहीं हूं कि संबंधित_ आवश्यक है, लेकिन मेरे पास टी सेट करने का समय नहीं था वह मेरे स्थानीय स्थापित पर पूरा अभ्यास। आप इसे बिना और बिना देख सकते हैं और देख सकते हैं कि आपको किस प्रकार के परिणाम मिलते हैं। –
इसके अलावा, अगर आप इस मार्ग पर जाना पसंद करते हैं, तो आपको यह प्रश्न देखना चाहिए। यह आपके द्वारा किए जा रहे कार्यों के आधार पर और दिखाता है, हालांकि मुझे अभी भी कम कमी होने की स्पष्टता मिलती है (fyi- प्रश्न में प्रश्न का उत्तर दिया गया है): http://stackoverflow.com/questions/6426383/rails- एसोसिएशन-डेटा-ऑन-द-एसोसिएशन-टेबल –