mardi 2 juin 2015

ember-data render belongsTo attribute

ember-cli 0.2.3; ember-data 1.0.0-beta.15

I'm struggling to figure out how to display attributes for a belongsTo object inside a template. I've found a few other similar questions here but they're either out of date or don't provide a solution.

User model: export default DS.Model.extend({ ... agency : DS.belongsTo("agency"), });

Agency model: var Agency = DS.Model.extend({ ... users: DS.hasMany("user"), });

User serializer: export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { agencies: { embedded: "always" } } });

ApplicationSerializer: export default DS.RESTSerializer.extend({});

The JSON (for index route) looks like so: { "users": [ { "id" : "1", "name" : "...", "agency_id": "6", "agencies" : [ { "id" : "6", "name": "...", ... } ] }, ... ] }

Although Ember isn't complaining, i'm not even sure that the data is coming in correctly because the documentation for EmbeddedRecordsMixin shows a belongsTo example as: { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } In any case, i can see that the agency data is included, although it seems that it has to be as an array, though there is only ever a single one per user. I haven't been able to find a complete explanation of precisely what format is expected.

However, the main thing is: How the heck do i display the agency name in a template?

Unsurprisingly, this doesn't work: {{#each user in model}} <tr> <td>{{user.get('agencies').firstObject().get("name")}}</td> <td>{{user.name}}</td> <td>{{user.email}}</td> </tr> {{/each}}




Aucun commentaire:

Enregistrer un commentaire