ruby-on-railsruby-on-rails-pluginsacts-as-tree

Acts as Tree with Multiple Models


I've got several models that I'd like to relate together hierarchically. For simplicity's sake, let's say I've got these three:

class Group < ActiveRecord::Base
  acts_as_tree
  has_many :users
end

class User < ActiveRecord::Base
  acts_as_tree
  belongs_to :group
  has_many :posts
end

class Post < ActiveRecord::Base
  acts_as_tree
  belongs_to :user
end

Under the current acts_as_tree, each node can individually can relate hierarchically to other nodes provided they are of the same type. What I'd like is to remove this restriction on type identity, so that SomePost.parent could have a User or a Post as its' parent, and that SomeUser.parent could have another user or a group as its parent.

Any thoughts?


Solution

  • The way I have done this in the past is by using a polymorphic container that lives in the tree, mapping to specific individual models.

    class Container < ActiveRecord::Base
       acts_as_tree
       belongs_to :containable, :polymorphic => true 
    end
    
    class User
      has_one :container :as => :containable
    end