Skip to content

Instantly share code, notes, and snippets.

@cfcosta
Created May 11, 2012 04:01
Show Gist options
  • Save cfcosta/2657452 to your computer and use it in GitHub Desktop.
Save cfcosta/2657452 to your computer and use it in GitHub Desktop.
module Tree
extend ActiveSupport::Concern
module ClassMethods
def leaves
where("children = ?::integer[]", [].pg)
end
def roots
where("ancestry = ?::integer[]", [].pg)
end
end
def add_child(attributes)
transaction do
child = self.class.create attributes.merge(ancestry: ancestry + [id])
update_attributes(children: children + [child.id])
child
end
end
def parents
self.class.where(id: ancestry)
end
def parent
self.class.find ancestry.last
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment