Jorge de los Santos
Jorge de los Santos

Reputation: 4643

Self referential association with attributes in ActiveRecord

I'm trying to replicate a relation where something can have many childrens, and many parents of itself with attributes.

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

I'm not able to create the methods to retrieve the childrens, and the parents of the items.

This is what I have so far:

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

I'm able to create the children for the Item, but the .parent method returns the childrens also:

Upvotes: 3

Views: 446

Answers (1)

ptd
ptd

Reputation: 3053

You need to change your Item class association to Decomposition by creating two direct has_many associations:

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

The way you have your code now, both the :children and :parent associations are referring to Decompositions where the Item is the parent. This solves that issue.

Upvotes: 2

Related Questions