与えられた2つの連結のActiveRecordの人々を通じて取得は、私は持つ人のモデル持っている人
belongs_to :from_person, :class_name => "Person"
belongs_to :to_person, :class_name => "Person"
人P1を考えると、私はインスタンスメソッドを実装したいですp1.pople_connecting_to(p2)p1を他の人に間接的にリンクするすべての人を返します。p2。
- P1 => P3 => P2
- P1 => P4 => P2
- P1 => P5 => P6 => P2
p1.people_connecting_to(p2)に[p3、p4]を返すようにします。 ActiveRecordを介して単一のSQLリクエストで達成することは可能ですか?
感謝:)
EDIT:
おかげでエドは、あなたの答えは次のソリューションに私をリードしています。私が追加しました:
has_many :to_relations, :source => :to_person, :through => :from_relationships
has_many :from_relations, :source => :from_person, :through => :to_relationships
と、このようなpeople_connecting_to
を実装:
def people_connecting_to(other_person)
to_relations.joins(:from_relationships).where(:"from_relationships_people.to_person_id" => other_person.id)
end