Best practise for extracting self referential many-to-many for ember data?


#1
//Setup:
Ember: 1.3.2
Handlebars: 1.3.0
jQuery: 2.0.0
-----------------
MongoDB (_id's, embedded data)

I have been attempting to get a self many to many relationship like this:

//Model:
App.Post = DS.Model.extend({
    title: DS.attr('string'),
    content: DS.attr('string'),
    links: DS.hasMany('App.Post'), 
});

Links should be embedded as id’s for (hopefully) obvious reasons.

After a couple of days digging around I have managed to get the app to serialise and submit the data correctly via RESTAdapter, the code I am using looks like this:

//Controller:
App.PostController = Ember.ObjectController.extend({
    actions: {
        addRelated: function(related) {
            var links = this.content.get('links').pushObject(related);
            this.content.save();
        }
    }
});

//Store:
App.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.extend({
        url: '/admin/api',
        serializer: DS.RESTSerializer.extend({
            primaryKey: function(type) {
                return '_id';
            },
            addHasMany: function(hash, record, key, relationship) {
                if (/_ids$/.test(key)) {
                    hash[key] = [];
                    record.get(this.pluralize(key.replace(/_ids$/, ''))).forEach(function(post) {
                        hash[key].push(post.get('id'));
                    });
                }
                return hash;
            }
        })
    });
});

From what I can gather the serializer is expecting data in the form

{post: {...}, links: [{...},{...}]}

But since the link is of type post, I would rather not create an entire App.Links model if possible.

So can I map links to posts? As in

{post: {...}, posts: [{...},{...}]}

I tried adding a deserializeHasMany but it didn’t get called when using App.Post.find()

I am guessing I would need to write a custom extract function that takes link_ids and extracts the posts into the record from it?

Sorry if I’m missing something basic, still wrapping my head around a lot of this.