与活动记录中的属性的自引用关联



我试图复制一种关系,其中某些东西可以有很多孩子,并且有许多具有属性的父母。

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

我无法创建方法来检索项目的子项和父项。

这是我到目前为止所拥有的:

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

我能够为项目创建子项,但 .parent 方法也返回子项:

您需要通过创建两个直接has_many关联将Item类关联更改为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 关联都是指Item是父级的Decompositions。这解决了这个问题。

最新更新