Question: get hierarchy of model having self refrenced parent children association rails

Question

get hierarchy of model having self refrenced parent children association rails

Answers 2
Added at 2016-12-27 09:12
Tags
Question

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

Answers
nr: #1 dodano: 2016-12-27 11:12

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

nr: #2 dodano: 2016-12-27 16:12

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
Source Show
◀ Wstecz