public
Last active

Recursion example in Ruby on Rails model. Recursion will generate array of parents parents

  • Download Gist
app-model-document.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
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
console
1 2 3 4
# Recursion will generate array of parents parents
d = Document.last
d.ancestors.collect(&:id)
# => [570, 569, 568]
db-migration-create_documents.rb
Ruby
1 2 3 4 5 6 7 8 9
class CreateDocuments < ActiveRecord::Migration
def change
create_table :documents do |t|
t.integer :parent_id
t.string :file
t.timestamps
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.