Defining a tree structure in ruby on rails

4

I'm developing a system in ruby on rails, and I'm stuck on one issue. My question is this: I need to create a tree, and then create my 'no' object and I would like it to have a 'no' parent and a 'no' child list. I tried the following approach:

    class No< ApplicationRecord
            belongs_to :arvore # Objeto pai
            belongs_to :pai, class_name: "No", primary_key: "pai_id" #Atributo do pai
    has_many :filhos, class_name: "No" ,foreign_key: "filho_id" # Lista de filhos
    end

But I could not define the parent or add the children. Could you guys give me a hint of what to do?

    
asked by anonymous 15.06.2017 / 19:56

1 answer

1

Assuming the table has a key for the parent (pai_id) define the relationships as follows:

class No < ApplicationRecord
  belongs_to :pai, class_name: "No"
  has_many :filhos, class_name: "No", foreign_key: :pai_id
end

And the tree model has the root node reference (have the root_id or no_id column)

class Arvore < ApplicationRecord
  belongs_to :raiz, primary_key: :no_id
end

So you can create:

raiz = No.new
filho1 = No.new(pai: raiz)
filho2 = No.new(pai: raiz)
filho_segundo_nivel = No.new(pai: filho1)

arvore = Arvore.new(raiz: raiz)
    
15.02.2018 / 23:08