Created
May 11, 2012 04:01
-
-
Save cfcosta/2657452 to your computer and use it in GitHub Desktop.
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.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