Ruby on rails 与ActiveRecord中属性的自引用关联

Ruby on rails 与ActiveRecord中属性的自引用关联,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我试图复制一种关系,在这种关系中,某个事物可以有很多孩子,而它本身也有很多父母 item1 x2-> item2 x3-> item3 x4-> item4 x2-> item1 x6-> item5 我无法创建检索子项和项的父项的方法 这就是我到目前为止所做的: class Decomposition < ActiveRecord::Base belongs_to :parent, :c

我试图复制一种关系,在这种关系中,某个事物可以有很多孩子,而它本身也有很多父母

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
类分解'Item',外键:'children\u omnicode'
属于\u to:child,:class\u name=>'Item',外键:'parent\u omnicode'
结束
类项:分解,源::子项
有多个:父级,:通过=>:分解,源::父级
结束

我可以为该项创建子项,但是.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 :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
类分解'Item',外键:'children\u omnicode'
属于\u to:child,:class\u name=>'Item',外键:'parent\u omnicode'
结束
类项:child\u分解,源::child
有多个:父级,:通过=>:父级\u分解,源::父级
结束

您现在拥有代码的方式是,
:子项
:父项
关联都是指
分解
,其中
是父项。这解决了这个问题。

除了我需要声明类的“<代码> PARTENSCORDESTATS:HasyMule:PARTYNSORDATABORD,CARRONGNONDE:”分解,FieldYouKE::PARTENTROMCONICODE 考虑编辑您的答案为未来的研究人员和谢谢。谢谢@ JorgedelosSantos我更新了答案。总有一些事情要忘记。