How to use hasMany on both sides (habtm)

I’m trying to learn new thing in ember every day and I’m stuck with ember-data and hasMany associations.


I want to add a tagging feature which means “add and remove tags to posts”. So I need a post model which hasMany tags. But the same tag can be used on different posts so a tag hasMany posts as well.


App.Post = Ember.Model.extend({
  title: DS.attr('string')
  body: DS.attr('string')
  tags: DS.hasMany('App.Tag')


App.Tag = Ember.Model.extend({
  name: DS.attr('string')
  posts: DS.hasMany('App.Post')

After trying to add a new tag to a post and commit it’s changes, my json payload misses always the post_id.

p = Post.find(1)
p.get('tags').createRecord({name: "test tag name"})

JSON sent to rails

{"tag"=>{"name"=>"test tag name"}}

Using a join model didn’t help and it feels like both are bad approaches at all.

I’ve read through the test specs of ember-data but there was no habtm or similar test case, so maybe it’s just not supported.


What is the ember way to define hasMany and belongsTo associations on both sides or is there a better way in general to solve my problem?

I tried to understand how ember-data is generating these payloads and tried to override addHasMany but it’s more guessing how it should work instead of understanding it. If ember-data doesn’t support habtm, I would be happy to solve it via pullrequest but I need some help first :slight_smile:

1 Like

This seems to have solved my issues regarding my HABTM relationship problems. Hopefully it’ll resolve your problems also.

Any hint for this similar problem?