1

I'm building an Ember.js app which allows Many-to-Many relationships between 2 entities, e.g. Post and Tag:

App.Post = DS.Model.extend({
    title: DS.attr("string"),
    body: DS.attr("string"),
    tags: DS.hasMany("App.Tag")
});

App.Tag = DS.Model.extend({
    name: DS.attr("string"),
    posts: DS.hasMany("App.Post")
});

I'm having difficulty getting Ember to serialize the many-to-many relationship when persisting new records. This is how I'm currently doing it:

// Create the post
post = store.createRecord(App.Post, {title: "Example", body: "Lorem ipsum..."});

// Create the tag
tag = store.createRecord(App.Tag, {name: "my-tag"});

// Add the tag to the post
post.get("tags").addObject(tag);

// Add the post to the tag
tag.get("posts").addObject(post);

// Save
store.commit();

The new records show up in the DOM, and are POSTed to my API, however the serialization doesn't include the relationship between them. For example, the serialization of the post looks like:

title=Example&body=Lorem+ipsum...

I would expect it to also include the tags it has been associated with.

Where am I going wrong?

wintron
  • 187
  • 1
  • 2
  • 9

2 Answers2

1

By default, hasMany relationships are only serialized to an _ids array in your JSON if you configure the relationship as embedded in your serializer. Take a look at this answer for more details.

Community
  • 1
  • 1
ahmacleod
  • 4,280
  • 19
  • 43
0

You can do it with Ember Data 1.0.0 by overriding the serializer: http://mozmonkey.com/2013/12/serializing-embedded-relationships-ember-data-beta/

Jeremy Gillick
  • 2,560
  • 3
  • 27
  • 35