Skip to content

Instantly share code, notes, and snippets.

@JulienBreux
Forked from equivalent/app-model-document.rb
Last active August 29, 2015 14:20
Show Gist options
  • Save JulienBreux/6216303d53c87332b4c2 to your computer and use it in GitHub Desktop.
Save JulienBreux/6216303d53c87332b4c2 to your computer and use it in GitHub Desktop.
class Document < ActiveRecord::Base
belongs_to :parent, class_name: 'Document'
def self.get_ancestors(who)
@tree ||= []
# @tree is instance variable of Document class object not document instance object
# so: Document.get_instance_variable('@tree')
if who.parent.nil?
return @tree
else
@tree << who.parent
get_ancestors(who.parent)
end
end
def ancestors
@ancestors ||= Document.get_ancestors(self)
end
end
# Recursion will generate array of parents parents
d = Document.last
d.ancestors.collect(&:id)
# => [570, 569, 568]
class CreateDocuments < ActiveRecord::Migration
def change
create_table :documents do |t|
t.integer :parent_id
t.string :file
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment