Hello,
I’m still experimenting with my first ember app. Now I’ve found a solution for the topics issue. However, I think there must be a smarter one.
Summary: I have two models which have a one to many relationship:
app/models/event.js:
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
appointments: DS.hasMany('appointment'),
});
app/models/appointment.js:
import DS from 'ember-data';
export default DS.Model.extend({
date: DS.attr('date'),
event: DS.belongsTo('event'),
});
Given the following data:
Appointments:
ID | Date | Event
1 | 2015-04-01 20:00 | 1
2 | 2015-04-30 19:00 | 1
3 | 2015-04-02 12:00 | 2
Events:
ID | Title | Appointments
1 | Event A | [1,2]
2 | Event B | [3]
When I just do a {{#each event in events}}
at my event template, I get two rows. One for each event.
However, my output has to be like this (note the sorting!):
2015-04-01 20:00 Event A
2015-04-02 12:00 Event B
2015-04-30 19:00 Event A
This is how my current solution looks like:
app/controllers/events.js:
import Ember from 'ember';
export default Ember.Controller.extend({
rows: function() {
var events = this.get('events'),
rows = [];
events.forEach(function(event) {
var appointments = event.get('appointments');
appointments.forEach(function(appointment) {
// Deep copy not working: var row = Ember.$.extend(true, {}, event);
var row = {id: event.get('id')};
row.date = appointment.get('date');
row.aid = appointment.get('id');
row.event = event;
rows.pushObject(row);
});
});
var rowsController = Ember.ArrayController.create({
content: rows,
sortProperties: ['date'],
sortAscending: true
});
return rowsController;
}.property('@each.appointments')
});
app/templates/events.hbs:
<div class="row">
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Title</th>
<th></th>
</tr>
</thead>
<tbody>
{{#if events}}
{{#each row in rows}}
<tr>
<td>
{{format-date row.date}}
</td>
<td>
{{row.event.title}}
</td>
<td>
{{#link-to "events.show" row.event}}Tickets{{/link-to}}
</td>
</tr>
{{/each}}
{{else}}
<tr><td colspan="3">No Events found.</td></tr>
{{/if}}
</tbody>
</table>
</div>
Is there any “Ember way” of doing this more nicely?
Kind regards, haggis