Timo
Timo

Reputation: 81

get hierarchy of model having self refrenced parent children association rails

I have a model Document with the following relationship

belongs_to :parent, class_name: 'Document'
has_many :children, class_name: 'Document', foreign_key: 'parent_id'

I wanna be able to call a method on document object to retrieve all of its parent and children. Is there a way to do this through active record

Upvotes: 0

Views: 455

Answers (2)

Timo
Timo

Reputation: 81

I ended up implementing these methods on the document model

def get_children(level = 0, result = [])
  result.push([level, self])
  if(!self.children.empty?)
    self.children.each do |child|
      child.get_children(level+1, result)
    end
  end
  if(level == 0)
    return result
  end
end

def get_parents(result = [])
  if self.parent.present?
    result.push(self.parent)
    self.parent.get_parents(result)
  else
    return result
  end
end

Upvotes: 0

Nikita Misharin
Nikita Misharin

Reputation: 2020

You may want to use closure_tree gem. It has a really convenient support for hierarchical structures

Upvotes: 1

Related Questions