Joshua Jenkins
Joshua Jenkins

Reputation: 335

Ember.js - Matching model data and has many relationship in controller

I'm trying to build a table component that displays all matching data. I don't know how to get this working.

I have multiple Platforms that have many Markets.

The model is easy:

model() {
  return this.store.findAll('platform', {include: 'markets'});
}

I can display check boxes so the user can select what platforms to compare and access the id's in the controller.

How do I go about getting the correct records from the model in the controller? I can't do this in the route because it depends on what platforms are selected.

I can use Ember Data:

this.get('store').findRecord('platform', id, {include: 'markets'})

But I can't figure out how to access the markets.

I tried enumerables also, but the same issue:

this.get('model').filterBy('id', id)

After this, what is a clean way to get the matching markets based on their name?

Upvotes: 0

Views: 54

Answers (1)

Paul Bishop
Paul Bishop

Reputation: 170

For your situation, you can access and compare the markets based on any selected platforms within your component. Each platform should have a relationship established to its associated markets within the model file. The relationship will allow you to access the markets off of the platform. For example, platform.get('markets') within a controller, component or {{platform.markets}} within a template. For a bit more detail on the rough process for implementing throughout the app files:

//Within the platform.js model just to set the basic relationship
markets: hasMany(),

//Within your controller.js build an array of selected platforms
selectedPlatforms: null,

actions: {
  selectPlatform(platform) {
    this.get('selectedPlatforms').pushObject(platform);
  },
}

//Within your template.hbs provide your component the array
{{matching-markets platforms=selectedPlatforms}}

//Within your component.js compare the platform markets
platforms: null,

matchingMarkets: computed('platforms', function() {
  const platform1Markets = this.get('platforms.firstObject.markets');
  const platform2Markets = this.get('platforms.lastObject.markets');
  return /* Compare platform1Markets against platform2Markets */;
}),

// Within the component.hbs
{{#each matchingMarkets as |market|}}
  {{market.name}}
{{/each}}

Please reference the below link to an EmberTwiddle to see a rough (slightly hacky) example that might provide some better insight: https://ember-twiddle.com/364d9c04d37593f4a7c40cccf065a8fc?openFiles=routes.application.js%2C

Upvotes: 1

Related Questions