Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjacency data structure to nested hash

I have the following model in rails:

class Model < ActiveRecord::Base
  # id — integer
  # name — string
  # model_id — integer

  belongs_to :parent, class_name: 'Model', foreign_key: 'model_id'
  has_many :children, class_name: 'Model', foreign_key: 'model_id'
end

I am using adjacency structure, which can have infinite depth. I am on a Postgres database using recursive selects.

What will be the most sane way to get a nested hash of objects? I tried to select instances of Model and sort them, yet could not bring this to any usable result.

Lets say I have four Model instances saved in my database: Model_1, Model_2, Model_3 and Model_4. Model_3 is a child of Model_2 and Model_4 is a child of Model_3.

Here is an output I am trying to achieve (a nested hash of Model instances):

{
  #<Model_1...> => {},
  #<Model_2...> => {
    #<Model_3...> => {
      #<Model_4...> => {}
    }
  }
}

Any ideas?

Update: Tree is already recovered — either as a CollectionProxy, Relation or any other array-ish data structure. I wan't to sort that tree into the hash of nested hashes.

like image 302
Ruslan Avatar asked Sep 17 '26 17:09

Ruslan


1 Answers

I would name it parent_id field.

  belongs_to :parent, class_name: "Model"
  has_many :children, class_name: "Model", foreign_key: "parent_id"

When you have the hash, you would use sort or sort_by:

http://www.ruby-doc.org/core-2.1.0/Enumerable.html#method-i-sort_by

def sort(hash)
  hash.sort { |m1, m2| m1.id <=> m2.id }
  sort(hash.children)
end
like image 56
Chloe Avatar answered Sep 20 '26 08:09

Chloe