iamtoc
iamtoc

Reputation: 1709

Rails 4 - How to dynamically reference an unknown table related to itself?

In an attempt to build an automated filter system for a dynamically generated index view, I came upon the need to handle related records on the same table, (for example, a Task belongs to Tasks through a parent_id field set as the foreign key. How would one reference the self associated table?

The 'klasses' example below is the illustration in question.

# Compile recursive array based on parent_id, 
# where parent_id is foreign_key on it's same table 

def build_recursive(conditions)
    @children = []
    klass = current_controller.singularize.constantize.where(conditions).all

    def fetch_subs(sub)            
        sub.klasses.where(conditions).order(:sort).each do |child| <-- how to dynamically reference 'klasses'?
            @children << child
            fetch_subs(child)
        end
        return @children
    end

    klass.klasses.each do |record|  <-- how to dynamically reference 'klasses'? 
        @children << record
        fetch_subs(record)  
    end

    return @children
end

How would one dynamically reference 'klasses' in this example, where klasses would be the related and same table of the current controller?

Also, if there is an existing gem or better solution altogether, I would gratefully accept additional suggestions. Thanks in advance.

Upvotes: 0

Views: 233

Answers (1)

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

Take a look for ancetry gem it will let you manage parent->children relations with ease.

Upvotes: 1

Related Questions