Mongoid "acts-as-tree" vs. "recursively_embeds_many" vs. "mongoid-tree"

mongoid, ruby, ruby-on-rails, tree

Solution

You can't use `mongoid-tree` and `recursively_embeds_many` together. You'll have to choose between a tree using references (`mongoid-tree`) or an embedded tree (`recursively_embeds_many`). If you want to embed the tree in other models I'd recommend the latter. If you want to reference music styles from other models (for example use them as categories and make them have many different artists) I'd recommend the `mongoid-tree` approach. In both cases you won't need the `parent` field.

So your example using `mongoid-tree` could look like this:

class Musicstyle
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Tree

  field :musicstyle, type: String
  field :description, type: String
end

# Usage example
musicstyle = Musicstyle.find(...)
musicstyle.children # This music style's children
musicstyle.parent   # This music style's parent

and your example using just `recursively_embeds_many` could look like this:

class Musicstyle
  include Mongoid::Document
  include Mongoid::Timestamps
  recursively_embeds_many

  field :musicstyle, type: String
  field :description, type: String
end

# Usage example
musicstyle = Musicstyle.find(...)
musicstyle.child_musicstyles # This music style's children
musicstyle.children.first.parent_musicstyle # The first child's parent (as you can't use find to get an embedded music style)

Bests,

Benedikt

Problem

I am quite new to mongoid and rails. So I have some troubles to get an tree structure working: I found three "solutions" to build mongoid-tree (which is the most actual one) https://github.com/benedikt/mongoid-tree and the mongoid provided solution recursively_embeds_more mongoid_acts_as_tree https://github.com/saks/mongoid_acts_as_tree my goal is to make a tree for musicstyles which can be referenced/embedded in different models. - -House - ---Tech House - ---Minimal House - -Folk - ---African - ---Asian - -Metal - ---Heavy Metal - ---Death Metal - ..... My Model looks now like this: ``` class Musicstyle include Mongoid::Document include Mongoid::Timestamps include Mongoid::Tree # mongoid-tree Version recursively_embeds_many # mongoids version itself field :musicstyle, type: String field :description, type: String field :parent end ``` and the view ``` <div class="field"> <%= f.label :parent %> <%= f.select :parent, Musicstyle.all.map { |m| [m.musicstyle, m._id] }, {:include_blank => "Select a parent (if needed)"} %> </div> ``` I searched now for hours for an working example, without success. Maybe someone can offer me some lines of code for a better understanding any help will make my day many, many thanks in advance

Original source