Search code examples
javascriptruby-on-railsember.jsember-dataancestry

Ember.js model to be organised as a tree structure


I am learning Ember.js, using a Rails backend. I'm looking to set up a tree structure for relating a Group model to itself (Sub-Groups). Since it's pretty mature, I'd like to link up the Ancestry gem for consumption on the Ember side.

Ancestry adds a string column called "ancestry" to my Group model, and returns a string of parent ids. How would one approach the setting up Ember models in this case?


Solution

  • I figured it out with some tinkering around with the group serializer and Ember model.

    # serializers/group_serializer.rb
    class GroupSerializer < ActiveModel::Serializer
      attributes :id, :name, :parents, :subgroups
    
      def parents
        object.ancestor_ids unless object.is_root?
      end
    
      def subgroups
        object.descendant_ids if object.has_children?
      end
    end
    
    # app/javascripts/models/group.js.coffee
    App.Group = DS.Model.extend
      name: DS.attr 'string'
      parents: DS.hasMany 'group'
      subgroups: DS.hasMany 'group'