Matching Genre Ids With Genre Names In Tmdb With Javascript (ember.js)
Solution 1:
I think your primary problem is that you're trying to fix something on the component layer that is better handled on the model layer.
While you can do that, what you actually want is a relationship from the movie
model to the genre
model:
genres: hasMany('genre'),
I'm not sure what your API provides 1:1 because you've not pasted the exact response. At some point you've mentioned a results
array, and the genres seems to be wrapped inside a genres
array. So if thats not 100% correct you maybe need to tweak this solution a bit.
For the start I would recommend the newer JSONSerializer
instead of the RESTSerializer
.
Now you need to tell ember that for the genres
relationship it should use the ids provided in the genre_ids
array. This can be done by keyForRelationship
:
importDSfrom'ember-data';
import {singularize} from'ember-inflector';
exportdefaultDS.JSONSerializer.extend({
...
keyForRelationship(key, typeClass, method) {
return`${singularize(key)}_ids`;
},
});
Here I use the ember-inflector
to get the singular of the relationship name (so genres -> genre
) and then just add _ids
. This is enough for ember to recognize the ids and then use them to provide the right model instances.
Next you can basically just loop over genres
on your movie
model:
{{#each movie.genres as |genre|}}
{{genre.name}}
{{/each}}
Now you don't even need to pass the list of all genres to the controller/template. However you still need to load them so ember-data
can use them. Otherwise ember-data
would try to fetch them individually when you use them.
So your model
hook could look like this:
model() {
returnRSVP.hash({
genres: this.store.findAll('genre'),
movies: this.store.findAll('movie'),
}).then(x => x.movies);
}
Here is a twiddle implementing this. However because I don't wanted to live-fetch the data I've created dummy adapters that return static data.
Post a Comment for "Matching Genre Ids With Genre Names In Tmdb With Javascript (ember.js)"