Skip to content

Instantly share code, notes, and snippets.

@pauln
Created January 23, 2018 04:38
Show Gist options
  • Save pauln/c3e87cfd52a05fa20fad8ba9b4e8b49a to your computer and use it in GitHub Desktop.
Save pauln/c3e87cfd52a05fa20fad8ba9b4e8b49a to your computer and use it in GitHub Desktop.
find-by-model
import Ember from 'ember';
const { inject: {service} } = Ember;
export default Ember.Controller.extend({
store: service(),
appName: 'Ember Twiddle',
init() {
this._super(...arguments);
let store = this.get('store');
store.pushPayload( {
"data": [
{
"attributes": {
"label": "Thingy 1"
},
"id": "1",
"relationships": {
"whatsits": {
"data": [
{
"id": "2",
"type": "whatsits"
}
]
}
},
"type": "thingys"
}
],
"included": [
{
"attributes": {
"label": "Whatsit 2"
},
"id": "2",
"relationships": {
"thingy": {
"data": {
"id": "1",
"type": "thingys"
}
}
},
"type": "whatsits"
}
]
});
this.set('thingys', store.peekAll('thingy'));
this.set('whatsits', store.peekAll('whatsit'));
this.set('whatsit', this.get('thingys').findBy('whatsit.id', this.get('whatsits')[0].get('id')));
}
});
import Ember from "ember";
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";
export default Model.extend({
whatsit: belongsTo('whatsit'),
whatsit_id: Ember.computed.alias('whatsit.id'),
label: attr('string')
});
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";
export default Model.extend({
label: attr('string'),
thingy: belongsTo('thingy')
});
<h1>Welcome to {{appName}}</h1>
<br>
{{#each thingys as |thingy|}}
{{thingy.label}} {{thingy.whatsit_id}}<br>
{{/each}}
<br>
{{#each whatsits as |whatsit|}}
{{whatsit.label}}<br>
{{#with (find-by 'whatsit' whatsit thingys) as |found|}}
Found by entity: {{found.label}}<br>
{{/with}}
{{#with (find-by 'whatsit.id' whatsit.id thingys) as |found|}}
Found by ID: {{found.label}}<br>
{{/with}}
{{#with (find-by 'whatsit_id' whatsit.id thingys) as |found|}}
Found by aliased ID: {{found.label}}<br>
{{/with}}
{{/each}}
{{whatsit.label}}
<br>
{{outlet}}
<br>
<br>
{
"version": "0.13.0",
"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.16.2",
"ember-template-compiler": "2.16.2",
"ember-testing": "2.16.2"
},
"addons": {
"ember-data": "2.16.3",
"ember-composable-helpers": "2.1.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment