Last active
October 29, 2018 07:47
-
-
Save equivalent/5063770 to your computer and use it in GitHub Desktop.
Recursion example in Ruby on Rails model. Recursion will generate array of parents parents
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
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 |
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
# Recursion will generate array of parents parents | |
d = Document.last | |
d.ancestors.collect(&:id) | |
# => [570, 569, 568] |
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
class CreateDocuments < ActiveRecord::Migration | |
def change | |
create_table :documents do |t| | |
t.integer :parent_id | |
t.string :file | |
t.timestamps | |
end | |
end | |
end |
The issue i has was each time i created a new instance of the object, it remembered the previous ancestors
this worked for me
def parents_id
parents = []
if parent
parents << parent.id
(parents << parent.parents).flatten
else
parents.flatten
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For some reason i had some issue with the code you had written
this is what worked for me:
`def ancestors
ancestors = []
ancestors = Klass.get_ancestors(ancestors, self)
end
def self.get_ancestors(ancestor, klass)
if klass.parent.nil?
return ancestor
else
ancestor << klass.parent
Klass.get_ancestors(ancestor, klass.parent)
end
end`