I’m trying to figure out the best Ember 2 way to display a list of associated records in a nested route for a single given record of a different type, and to be able to modify the list (by adding or deleting associated records) so that the template updates to show the latest list. For now I’m just concentrating on deleting associated records.
As a concrete example of what I have so far, say an author has many books and they are displayed in a nested route, /authors/:author_id/books
:
// routes/authors/books.js
import Ember from 'ember'
export default Ember.route.extend({
model () {
const author = this.modelFor('authors')
return Ember.get(author, 'books').sortBy('title')
},
actions: {
deleteBook (book_id) {
const author = this.modelFor('authors')
const filteredBooks = Ember.get(author, 'books').filter(
book => Ember.get(book, 'id') === book_id
)
if (filteredBooks.length < 1) { return }
// At this point just delete locally in client app.
filteredBooks[0].deleteRecord()
console.log(Ember.get(filteredBooks[0], 'isDeleted')) // true
}
}
}
An author’s books are displayed by a template:
// templates/authors/books.hbs
<ul>
{{#each model as |book|}}
<li>
<button {{action 'deleteBook' book.id}}>🗑</button>
{{book.title}}
</li>
{{/each}}
</ul>
This works as far as displaying the initial list of books in the template, finding the correct book in the deleteBook
method, and calling deleteRecord
on it. Afterward, the isDeleted
proeprty of the book returns true.
However, the list of books rendered in the template doesn’t change, and repeated clicks on the delete button for a single book continue to find and re-“delete” the book on every click. Can anyone shed any light on why this isn’t working as I expect? Is this a decent approach, or is there a different way I should be using Ember to accomplish the desired outcome?