1
votes

From looking at various questions at SO, I understand that there have been issues with ember and hasMany relationships. I'm using ember-data 1.0.0-beta.12, and I'm trying to understand what the current state of things are.

My app has a Player model and a Tournament model, and tournaments have multiple players & players can be in multiple tournaments. Here are my models:

var Player = DS.Model.extend({
  name: DS.attr('string'),
  tournaments: DS.hasMany('tournaments', {async: true}),
});

var Tournament = DS.Model.extend({
  title: DS.attr('string'),
  players: DS.hasMany('player', {async: true}),
});

I have a template that lists the players in a tournament:

{{#each player in players}}
    <a class="list-group-item" href="#" {{action 'removePlayer' NOT_SURE_WHAT_MODEL_TO_PASS}}>
      {{player.name}}
    </a>
{{/each}}

I'm starting to define my removePlayer action, but I'm stuck. I can pass either the tournament, or the player to the action, but it seems that I need both. And then once I have them, I have no idea what methods may be used to remove the relationship, I can't find anything about that in the docs, and it see all sorts of approaches on the web.

How to I pass both the player and the tournament model to my controller? And what is the most straightforward way to remove the association without deleting either record?

I'm using ember-cli 0.1.5, with the following versions:

DEBUG: -------------------------------
ember.js:15373 DEBUG: Ember      : 1.8.1
ember.js:15373 DEBUG: Ember Data : 1.0.0-beta.12
ember.js:15373 DEBUG: Handlebars : 1.3.0
ember.js:15373 DEBUG: jQuery     : 1.11.2
ember.js:15373 DEBUG: -------------------------------
1

1 Answers

2
votes

You can pass both the tournament and the player to the action:

{{#each player in players}}
    <a class="list-group-item" href="#" {{action 'removePlayer' player tournament}}>
      {{player.name}}
    </a>
{{/each}}

And then in your controller implement an action which takes multiple parameters:

  actions: {
    removePlayer: function(player, tournament) {
      tournament.get('players').removeObject(player);
      // you can save the tournament and player here, unless you are handling that as part of another action
    }
  }