Skip to content

Instantly share code, notes, and snippets.

@cfcosta
Created May 11, 2012 21:18
Show Gist options
  • Save cfcosta/2662467 to your computer and use it in GitHub Desktop.
Save cfcosta/2662467 to your computer and use it in GitHub Desktop.
An implementation of Trees for PostgreSQL
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.new attributes
child.ancestry = ancestry + [id]
child.save
self.children = children + [child.id]
save
child
end
end
def destroy
unless children.empty?
raise ActiveRecord::DeleteRestrictionError,
"can not delete items with children"
end
transaction do
parent.children = parent.children - [id]
parent.save!
super
end
end
def parents
@parents ||= self.class.where(id: ancestry)
end
def parent
@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