Ember.js model to be organised as a tree structure

2019-07-18 08:45发布

问题:

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?

回答1:

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'