Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Persist Local Relationship Changes
import DS from 'ember-data';
import Ember from 'ember';
export default DS.JSONAPIAdapter.extend({
findRecord() {
return Promise.resolve({
data: {
type: 'person',
id: '1',
attributes: {
firstName: 'Chris',
lastName: 'Thoburn'
},
relationships: {
roles: {
data: [{ type: 'role', id: '2' }]
}
},
},
included: [
{
type: 'role',
id: '2',
attributes: {
title: 'Hacker'
}
}
]
});
},
updateRecord(store, modelClass, snapshot) {
console.log(snapshot.changedAttributes());
return Promise.reject({
errors: ['everything is bad']
});
}
});
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Persist Local Relationship Change Example',
init() {
this._super();
this.record = this.get('store').findRecord('person', 1);
},
actions: {
saveNewRole(title) {
const newRole = store.createRecord('role', { title }); trueRecord.save()
.catch((e) => {
trueRecord.rollbackAttributes();
});
}
}
}
});
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";
export default Model.extend({
firstName: attr(),
lastName: attr(),
roles: hasMany('role', { async: false, inverse: null }),
});
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";
export default Model.extend({
title: attr(),
});
export default class Serializer {
normalizeResponse(_, __, data) {
return data;
}
static create() {
return new Serializer();
}
}
<h1>Welcome to {{appName}}</h1>
<br>
<h1>{{record.firstName}} {{record.lastName}}</h1>
<h2>Roles</h2>
<ul>
{{#each record.roles as |role|}}
<li>{{role.title}}</li>
{{/each}}
</ul>
<hr>
Add Role: {{input value=title}}
<button {{action "saveNewRole" title}}>Save</button>
{{outlet}}
<br>
<br>
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "~2.13.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.