How can you set an hasMany relationship with limits?


#1

I posted this question on stackoverflow, but didn’t find a solution so I thought I’d give it a try here. I have a bit of a weird case and I’m not sure how to handle it.

Let’s say I have a bunch of Containers and each container hasMany items, but they only have so many item_slots. For instance, one container could have 3 slots while another only has 1.

App.Container = DS.Model.extend({
  name:DS.attr('string'),
  item_slots:DS.attr('number'),
  items:DS.hasMany('item')
});

App.Container.FIXTURES = [
  {id:1, name:'Container 1', item_slots:3},
  {id:2, name:'Container 2', item_slots:4},
  {id:3, name:'Container 3', item_slots:1}
];

And then I have a list of Items that can go into these slots.

App.Item = DS.Model.extend({
  name:DS.attr('string')
});

App.Item.FIXTURES = [
  {id:1,name:'Item 1'},
  {id:2,name:'Item 2'},
  {id:3,name:'Item 3'},
  {id:4,name:'Item 4'}
];

I’ve created a jsBin here as for an example of what I’m trying to do, but it’s not complete. I’ve commented out the part that I’m stuck on.

I’ve created a component that provides a drop down of all the different items that can be selected. My question is really how can I loop over the device_slots for each Container? Then I can create an item-selector for each device_slot.

I’m developing the API for this, as well, so if there’s anyway I can modify that to help with this issue, that’d be totally possible. Currently, the payload is something like this:

{ "containers":
   [{id:1,name:'Container 1',item_slots:3},
   {id:2,name:'Container 2',item_slots:4},
   {id:1,name:'Container 3',item_slots:1}]
}

It use to be like this:

{ "containers":
   [{id:1,name:'Container 1',items:[1,2,3]},
   {id:2,name:'Container 2',items:[1,2,3,4]},
   {id:1,name:'Container 3',items:[1]}]
}

Until I started really working with it and realized that Ember was automatically relating the Items (which is awesome!). I tried changing my API so that items was just an array with empty strings or NULL that I could still loop over with #each, but I kept getting an error stating that all items hadn’t been loaded. I changed to item_slots to avoid the relation issue.

I attempted to create a for loop helper to take care of this, but couldn’t quite figure it out. When I saw that block helpers weren’t supported, I felt like I was going the wrong direction. I’ve been trying to think of how I could use a view or even a component to accomplish this, but I don’t see it. I have this sort of thing in several places in my app and don’t have to have to write tons of specialty classes to handle each case.

Any and all input, ideas and help would be deeply appreciated! Thanks!!