Ruby on rails:Has_many self referencial - 在视图中列出对象

时间:2016-06-26 11:39:41

标签: ruby-on-rails ruby bidirectional

我正在做这个教程http://cobwwweb.com/bi-directional-has-and-belongs-to-many-on-a-single-model-in-rails,为每个孩子做多个父母的亲子关系。

我已经可以将父母与孩子联系起来了。但现在我不明白如何列出父母及其子女

这是我的PerformanceIndicator模型:

>>> def foo():
...     return 'b', 'c', 'd'
...
>>> bar = ['a', 'e']
>>> bar[1:1] = foo()
>>> bar
['a', 'b', 'c', 'd', 'e']
>>> ['a'] + list(foo()) + ['e']
['a', 'b', 'c', 'd', 'e']
>>> ['a', *foo(), 'e']
['a', 'b', 'c', 'd', 'e']

这是我的PerformanceIndicatorAssociation模型:

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

如何列出这样的父母及其子女?

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

1 个答案:

答案 0 :(得分:0)

假设left_associations是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