How would you Structure ActiveStorage::Attachment in a tree

Hi, I am looking for experience and similar solutions to a problem.

Authors on our platform upload projects. They would like to organize their files in “folders”. I was thinking of using Active Storage and introducing an object like MyActiveStorage::Folder. In this way I could give structure to the files. The folders are records in the db and each folder knows its files and subfolders. So actually a record could have

class Article < ApplicationRecord 
has_many_attached :files
has_root_folder :root_folder # or something similar that knows that attachment on the first level and its children and is basically a tree structure in db.

Article knows all of its files linearly while by accessing “:root_folder” you can access list them as a tree.

My question is - do you know of anything similar to that. Anything I could look for more inspiration on this problem and the solutions others have thought of?


I’d keep the file / folder structure separate from AS. Eg:

class ProjectFolder < ApplicationRecord
  belongs_to :article
  belongs_to :parent_folder, optional: true
  has_many :project_files
  has_many :files, through: :project_files

  validates :parent_folder, presence: true, unless: -> { root_folder? } 

class ProjectFile < ApplicationRecord
  belongs_to :project_folder
  has_one_attached :file

Another approach might be to model it as a directory tree, but preloading data will be tricky.

class DirectoryNode < ApplicationRecord
  belongs_to :parent, class: 'DirectoryNode'
  belongs_to :article

  has_many :children, class: 'DirectoryNode'
  has_one :file

Thanks. That seems nice.