I use the following code to reload a Switchboard every x milliseconds. Can I tell ember-data to reload the SwitchboardEntrys which are in a hasMany relation to Switchboard recursively?
app.js
App = Ember.Application.create({
ready: function() {
if (reload_interval != 0) {
var switchboard = App.Switchboard.find(switchboard_id);
setInterval(function() {
switchboard.reload();
}, reload_interval);
}
}
});
App.Store = DS.Store.extend({
revision: 12
});
DS.RESTAdapter.configure("plurals", {
switchboard_entry: "switchboard_entries"
});
App.Switchboard = DS.Model.extend({
switchboardEntrys: DS.hasMany('App.SwitchboardEntry'),
name: DS.attr('string')
});
App.SwitchboardEntry = DS.Model.extend({
switchboard: DS.belongsTo('App.Switchboard'),
name: DS.attr('string'),
path_to_user: DS.attr('string')
});
Related
Let's say we have many medicines that can be prescribed to many patients. Our model would look like this:
App.Medicine = DS.Model.extend({
name: DS.attr(),
patients: DS.hasMany('user', { async: true }),
});
App.User = DS.Model.extend({
name: DS.attr(),
medicines: DS.hasMany('medicine', { async: true })
});
In this scenario, how do we save records to a Firebase store?
App = Ember.Application.create();
App.ApplicationAdapter = DS.FirebaseAdapter.extend({
firebase: new Firebase('https://YOUR_FIREBASE.firebaseio.com/')
});
App.Router.map(function(){ });
App.Medicine = DS.Model.extend({
name: DS.attr(),
patients: DS.hasMany('user', { async: true }),
});
App.User = DS.Model.extend({
name: DS.attr(),
medicines: DS.hasMany('medicine', { async: true })
});
App.IndexRoute = Ember.Route.extend({
model: function() {
var medicines = this.store.find('medicine');
var users = this.store.find('user');
return {
medicines: medicines,
users: users
};
},
actions: {
savePost: function(){
var store = this.store;
var medicine1 = store.createRecord('medicine', {name: 'aspirin'});
var patient1 = store.createRecord('user', {name: 'Jane'});
var patient2 = store.createRecord('user', {name: 'Peter'});
medicine1.save()
.then(function(){
return Ember.RSVP.Promise.all([
patient1.save(),
patient2.save()
])
.then(function(){
var promises = [];
var patientsOfMedicine1 = medicine1.get('patients');
var medicinesOfPatient1 = patient1.get('medicines');
var medicinesOfPatient2 = patient2.get('medicines');
promises.push(patientsOfMedicine1, medicinesOfPatient1, medicinesOfPatient2);
return Ember.RSVP.Promise.all(promises);
})
.then(function(arrayOfAttachedArrays){
var promises = [];
var patientsOfMedicine1 = arrayOfAttachedArrays[0];
var medicinesOfPatient1 = arrayOfAttachedArrays[1];
var medicinesOfPatient2 = arrayOfAttachedArrays[2];
patientsOfMedicine1.addObjects(patient1, patient2);
medicinesOfPatient1.addObject(medicine1);
medicinesOfPatient2.addObject(medicine1);
promises.addObjects(medicine1.save(),patient1.save(),patient2.save());
return Ember.RSVP.Promise.all(promises);
});
});
}
}
});
Notes:
Thanks to David Govea for showing me how this works.
If there's a better way to do this, please post below.
I have an ember model Category:
export default DS.Model.extend({
name: DS.attr('string'),
img: DS.attr('string'),
url: DS.attr('string'),
cnt: DS.attr('number'),
// parent_id: DS.belongsTo('category', {
// inverse: 'children',
// async: true
// }),
parent_id: DS.attr('string'),
// children: DS.hasMany('category', {
// inverse: 'parent_id',
// async: true
// }),
children: DS.attr(),
isSelected: false,
isExpanded: false,
hasChildren: function() {
return this.get('children').get('length') > 0;
}.property('children').cacheable(),
isLeaf: function() {
return this.get('children').get('length') == 0;
}.property('children').cacheable()
});
In my index route I have:
export default Ember.Route.extend({
model: function() {
var store = this.store;
return Ember.ArrayProxy.create({
categories: store.find('category'),
menuTopCategories: store.find('category', { parent_id: 1 })
});
}
});
I'm using a RESTAdapter so the store.find will send two requests to the server: categories and categories?parent_id=1.
I would like to have only the first request and then filter through the categories. I tried store.all - since I saw it reuses the already fetch data, but I can't manage to apply the filter.
I've rewritten the menuTopCategories and I don't see a new request:
menuTopCategories: store.filter('category', function(category) {
return category.get('parent_id') === "1";
})
My problem right now is to get the root category (first one) without hardcoding the parent_id.
Hey I'm having trouble dynamically loading fixture data into my emberjs models. How should I go about doing this? The addArtist function at the bottom will add one song correctly but I'm not sure how to adapt this to loading all of the songs into the data store correctly. Is there an easier way than adding each one individually?
App.Store = DS.Store.extend({
revision: 13,
adapter: 'DS.FixtureAdapter'
});
App.Artist = DS.Model.extend({
name: DS.attr('string'),
tracks: DS.hasMany('App.Tracks')
});
App.Tracks = DS.Model.extend({
videoid: DS.attr('string'),
title: DS.attr('string'),
duration: DS.attr('number')
});
App.Artist.FIXTURES = [];
App.Tracks.FIXTURES = [];
App.loadFixtures = function(){
$.getJSON('/artists', function(data){
$.each(data.artists, function(i,v){
App.Artist.createRecord(v);
});
});
$.getJSON('/tracks', function(data){
$.each(data.tracks, function(i,v){
App.Tracks.createRecord(v);
});
});
};
App.addArtist = function(){
var artist = App.Artist.createRecord({
id: 3,
name: 'Justin Martin'
});
var track = App.Tracks.createRecord({
id: 300,
title: 'Jungle Mix',
duration: 200
});
artist.get('tracks').pushObject(track);
};
Sample JSON Responses:
{"artists":[
{"id":1,"name":"The (International) Noise Conspiracy","track_ids":[1,2,3,4]},
{"id":2,"name":"0SM","track_ids":[5]},
{"id":3,"name":"2am","track_ids":[6,7,8]}
]}
{"tracks":[
{"id":1,"videoid":"FyjmCg_VMU0","title":"Smash It Up","duration":197},
{"id":2,"videoid":"jKXWm9yi4DY","title":"Only Lovers Left Alive","duration":162},
{"id":3,"videoid":"fwbleH55CCk","title":"Up For Sale","duration":211},
{"id":4,"videoid":"50JdKhIB1EQ","title":"A New Morning, Changing Weather","duration":270},
{"id":5,"videoid":"bd6ve0ydHVo","title":"The Landing feat. Alex G - Original Mix","duration":322},
{"id":6,"videoid":"RnwVtbMW4x4","title":"Anxious","duration":238},
{"id":7,"videoid":"Yo0zsqa06ZE","title":"I Did Wrong","duration":305},
{"id":8,"videoid":"_9ydBAgg130","title":"I Love You (feat. Baekchan & Joohee)","duration":219}
]}
Should I include the track_ids in the Artists response or do they get added when I call this method?
artist.get('tracks').pushObject(track);
I'm trying to update my model with ember-data like this (jsBin):
App = Ember.Application.create({
ready: function() {
var post = App.Post.find(1);
post.one('didLoad', function() {
post.set('name', 'my new name');
post.save();
});
}
});
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.FixtureAdapter
});
App.Post = DS.Model.extend({
name: DS.attr('string')
});
App.Post.FIXTURES = [
{id: '1', name: 'first post'}
];
and I get the following error in Chrome:
Uncaught Error: Attempted to handle event `didCommit` on <App.Post:ember226:1> while in state rootState.loaded.updated.uncommitted. Called with undefined
Is there something wrong or this is a bug ?
When I save a User all current dirty Users are commited. What do I have to change that a save only commits the transaction for that specific User?
app.js
App = Ember.Application.create();
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.FixtureAdapter'
})
App.Router.map(function() {
this.resource('users', function() {
this.resource('user', { path: ':user_id' })
})
});
App.UsersRoute = Ember.Route.extend({
model: function() {
return App.User.find();
}
});
App.UserController = Ember.ObjectController.extend({
startEditing: function() {
this.transaction = this.get('store').transaction();
this.transaction.add(this.get('content'));
},
save: function( user ) {
user.transaction.commit();
}
})
App.User = DS.Model.extend({
lastName: DS.attr('string')
})
App.User.FIXTURES = [{
id: 1,
lastName: "Clinton"
}, {
id: 2,
lastName: "Obama"
}]
My guess is that startEditing is never called, otherwise this would probably be ok.
The other option is that you save multiple times the record. Once a record is saved, it is moved back to the store's default transaction. Any subsequential call to save would actually commit the store's transaction.