Created
May 11, 2012 21:18
-
-
Save cfcosta/2662467 to your computer and use it in GitHub Desktop.
An implementation of Trees for PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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