2016-06-26 1 views
0

私はこのチュートリアルhttp://cobwwweb.com/bi-directional-has-and-belongs-to-many-on-a-single-model-in-railsを、各子供の複数の親との親子関係を行うために使っています。Ruby on Rails:Has_many自己参照 - オブジェクトを表示する

私はすでに親を子と関連付けることができます。

class PerformanceIndicator < ActiveRecord::Base 
    has_many :improvement_actions 
    has_ancestry 


    has_many :left_parent_associations, :foreign_key => :left_parent_id, :class_name => 'PerformanceIndicatorAssociation' 
    has_many :left_associations, :through => :left_parent_associations, :source => :right_parent 

    has_many :right_parent_associations, :foreign_key => :right_parent_id, :class_name => 'PerformanceIndicatorAssociation' 
    has_many :right_associations, :through => :right_parent_associations, :source => :left_parent 

    def associations 
    (left_associations + right_associations).flatten.uniq 
    end 
end 

そして、これが私のPerformanceIndicatorAssociationモデルです:

class PerformanceIndicatorAssociation < ActiveRecord::Base 
    belongs_to :left_parent, :class_name => 'PerformanceIndicator' 
    belongs_to :right_parent, :class_name => 'PerformanceIndicator' 
end 

どのようにすることができます。しかし、今、私は両親とその子供たち

を一覧表示することができます。これは、私のPerformanceIndicatorモデルであるかを理解していません両親とその子供をこのようにリストアップするか? left_associationsを想定し

Parent1 
    Child1 
    Child2 
Parent2 
    Child1 
    Child2 
+0

_Sidenote:_これは決して 'has_and_belongs_to_many'関係ではなく、2つの独立した' has_many'関係です。 – mudasobwa

答えて

0

がPerformanceIndicatorの親であり、right_associationsは子供である、あなたの範囲は、このように見える必要があります:

scope :without_parents, -> { 
    joins("LEFT JOIN performance_indicator_associations ON performance_indicator_associations.left_parent_id = performance_indicators.id") 
    .where(performance_indicator_associations: {right_parent_id: nil}) 
} 

を今、あなたは、次の結果が得られます。

pi1 = PerformanceIndicator.create(name: 'parent1') 
pi2 = PerformanceIndicator.create(name: 'parent2') 

ci1 = PerformanceIndicator.create(name: 'child1') 
ci2 = PerformanceIndicator.create(name: 'child2') 

pi1.right_associations << ci1 
pi1.right_associations << ci2 
pi2.right_associations << ci2 

PerformanceInficator.withour_parents.each do |parent| # => [p1, p2] 
    # do stuff with parent 
    parent.right_associations.each do |child| 
    # do stuff with child 
    # assume child is ci2 
    child.left_associations # => [p1, p2] 
    end 
end