Defining a tree structure in ruby on Rails

Asked

Viewed 188 times

5

I’m developing a system in ruby on Rails, and I’m stuck on a question. 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. 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 couldn’t define the father or add the children. Could you give me a hint of what to do?

  • You can show the table structure "in"?

  • If it can include the structures and models for the class arvore also helps.

  • I believe you can easily do using the Gem Ancestry

1 answer

1

Supposing that the table us has a key for the parent (pai_id), define 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 template has the root node reference (have the raiz_id or no_id column)

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

So Voce 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.