与 ActiveRecord 中的属性的自引用关联

Self referential association with attributes in ActiveRecord

我正在尝试复制一个关系,其中某些东西可以有很多 children,并且它本身有很多 parent 和属性。

item1 x2-> item2
      x3-> item3 x4-> item4 x2-> item1
                            x6-> item5

我无法创建检索项目的 children 和 parent 的方法。

这是我目前拥有的:

class Decomposition < ActiveRecord::Base
 belongs_to :parent, :class_name => 'Item', foreign_key: 'children_omnicode'
 belongs_to :child, :class_name => 'Item', foreign_key: 'parent_omnicode'    
end

class Item < ActiveRecord::Base
  has_many :decompositions, foreign_key: :parent_omnicode
  has_many :children, :through => :decompositions, source: :child
  has_many :parents, :through => :decompositions, source: :parent
end

我可以为项目创建 children,但是 .parent 方法 returns childrens 也可以:

您需要通过创建两个直接 has_many 关联,将 Item class 关联更改为 Decomposition

class Decomposition < ActiveRecord::Base
 belongs_to :parent, :class_name => 'Item', foreign_key: 'children_omnicode'
 belongs_to :child, :class_name => 'Item', foreign_key: 'parent_omnicode'    
end

class Item < ActiveRecord::Base
  has_many :parent_decompositions, class_name: "Decomposition", foreign_key: :parent_omnicode
  has_many :child_decompositions, class_name: "Decomposition", foreign_key: :children_omnicode
  has_many :children, :through => :child_decompositions, source: :child
  has_many :parents, :through => :parent_decompositions, source: :parent
end

您现在拥有代码的方式,:children:parent 关联都指的是 Decompositions,其中 Item 是父级。这解决了那个问题。