EmberJS error deleting record from model - ember.js

When I delete an item from my database, I get the following error
Attempted to handle event `pushedData` on <app#model:mymodel::ember851:myid> while in state root.deleted.inFlight.
But sometimes the error change to:
Error: Attempted to handle event `notFound` on <app#model:mymodel::ember851:myid> while in state root.deleted.saved.
My model is:
export default Model.extend({
position: attr('number'),
name: attr('string'),
shared: attr('boolean', { defaultValue: false }),
color: attr(),
textColor: attr(),
permissions: attr(),
calendarstack: belongsTo('calendarstack'),
event: hasMany('event'),
isActive: attr()
});
And my code to delete the record:
delete: function(type, id){
var that = this;
this.store.findRecord(type, id).then(function(data) {
data.deleteRecord();
data.save();
});
}

Related

How to load dependencies in Ember Data

I have an application, with 2 models: Team and User. Each team has many users, and only 1 Team Leader. On the Index view for Teams, I want to display the list of Teams, and the name of the Team leader. I can't get the name of the team leader to be displayed. Not sure what's wrong.
User Model:
export default Model.extend({
firstName: attr(),
lastName: attr(),
team: belongsTo('team', { inverse: 'users' }),
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
Team Model:
export default Model.extend(Validations, {
name: attr(),
shortName: attr(),
description: attr(),
teamLeader: belongsTo('user', { inverse: null }),
users: hasMany('user'),
specialisationArea: attr(),
sourceEnergyTeam: attr(),
isEnergyTeam: Ember.computed('specialisationArea', function(){
return this.get('specialisationArea') == 101;
})
});
Team Index Route:
export default Ember.Route.extend({
model() {
return this.store.findAll('team');
}
});
Team List Template:
{{#each model as |team|}}
<tr>
<td>{{team.name}}</td>
<td>{{team.shortName}}</td>
<td>{{team.description}}</td>
<td>{{team.teamLeader.fullName }}</td>
<td>{{#link-to "teams.team" team}}Details{{/link-to}}</td>
</tr>
{{/each}}
And this is the mirage configuration:
this.get('/teams', () => {
return [{
id : 11,
type: 'team',
name: 'Energy',
description: 'energy desc',
shortName: 'short',
teamLeader: 12,
users: [12],
energyTeam: true
}];
});
this.get('/teams/:team_id', () => {
return {
id: 11,
type: 'team',
name: 'energy',
description: 'energy desc',
shortName: 'eg',
teamLeader: 12,
users: [12],
energyTeam: true
};
});
this.get('/users', () => {
return [{
id: 12,
type: 'user',
firstName: 'Pedro',
lastName: 'Alonso',
team: 11
}];
});
I'm not sure what's going wrong, but in the network calls I can see that only a call to '/teams' is being triggered. Any ideas?
Thanks

Ember model find records without server request

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.

Ember.js error when saving one-to-many relationship model

I have problem creating record on one-to-many relationship. I use Ember 1.7 with Ember Data 1.0.0-beta.10.
app/models/transaction.js
import DS from 'ember-data';
var Transaction = DS.Model.extend({
code: DS.attr('string'),
created_at: DS.attr('date', {
defaultValue: function() { return new Date(); }
}),
customer: DS.belongsTo('customer', { embedded: 'always', async: true }),
details: DS.hasMany('transactiondetail', { embedded: 'always', async: true }),
is_cash_payment: DS.attr('boolean')
});
export default Transaction;
app/models/transactiondetail.js
import DS from 'ember-data';
var TransactionDetail = DS.Model.extend({
item: DS.belongsTo('item', { embedded: 'always', async: true }),
max_returned_at: DS.attr('date'),
returned_at: DS.attr('date'),
price: DS.attr('number')
});
export default TransactionDetail;
app/serializers/transaction.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
customer: { serialize: 'records', deserialize: 'id' },
details: { serialize: 'records', deserialize: 'ids' }
}
});
app/serializers/transactiondetail.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
item: { serialize: 'records', deserialize: 'id' },
}
});
app/controllers/transaction/create.js
import Ember from 'ember';
export default Ember.ObjectController.extend(, {
needs: ['transactions'],
transactionCode: '',
dateNow: new Date(),
maxReturnedAt: maxReturnedAt,
selectedItem: [],
selectedCustomer: null,
totalPrice: totalPrice,
payValue: 0,
change: 0,
isCashPayment: true,
actions: {
create: function() {
var self = this;
var record = this.store.createRecord('transaction', {
code: this.get('transactionCode'),
customer: this.get('selectedCustomer'),
is_cash_payment: this.get('isCashPayment')
});
this.get('selectedItem').forEach(function( item ) {
var transactionDetail = self.store.createRecord('transactiondetail', {
item: item,
max_returned_at: self.get('maxReturnedAt'),
price: item.get('price')
});
record.get('details').then(function(selectedRecord) {
selectedRecord.pushObject( transactionDetail );
});
});
record.save().then( function() {
self.get('controllers.transactions.model').pushObject({});
self.clearForm();
self.transitionToRoute('transactions');
});
},
goBack: function() {
this.transitionToRoute('transactions');
},
}
});
If I do create record, I got an error like this.
Error: Assertion Failed: The content property of DS.PromiseArray should be set before modifying it
at new Error (native)
at Error.EmberError (http://machine.dev:4200/assets/vendor.js:26712:23)
at Object.Ember.assert (http://machine.dev:4200/assets/vendor.js:16896:15)
at EmberObject.extend._replace (http://machine.dev:4200/assets/vendor.js:45514:15)
at EmberObject.extend._insertAt (http://machine.dev:4200/assets/vendor.js:45529:14)
at EmberObject.extend.pushObject (http://machine.dev:4200/assets/vendor.js:45573:14)
at apply (http://machine.dev:4200/assets/vendor.js:31554:27)
at superWrapper [as pushObject] (http://machine.dev:4200/assets/vendor.js:31132:15)
at eval (pw-store/controllers/transactions/create.js:74:35)
at Array.forEach (native) vendor.js:27637logToConsole vendor.js:27637RSVP.onerrorDefault vendor.js:41089__exports__.default.trigger vendor.js:59652Promise._onerror vendor.js:60651publishRejection vendor.js:58914(anonymous function) vendor.js:42243DeferredActionQueues.invoke vendor.js:13808DeferredActionQueues.flush vendor.js:13858Backburner.end vendor.js:13321Backburner.run vendor.js:13376apply vendor.js:31557run vendor.js:30173__exports__.default.EmberObject.extend._bubbleEvent vendor.js:50350(anonymous function) vendor.js:50298jQuery.event.dispatch vendor.js:4759jQuery.event.add.elemData.handle vendor.js:4427
Uncaught Error: Assertion Failed: Error: Assertion Failed: The content property of DS.PromiseArray should be set before modifying it
UPDATE
I have update my Ember Data to 1.0.0-beta.11 as suggested by Kingpin2k, but I got undefined error (see my comment below). I guess I do mistake on model and/or serializer but I have no idea how to fix it. Any help?

createRecord with ember-data + ember-data-django-rest-adapter

I'm currently working on creating an ember application using ember/ember-data/ember-data-django-rest-adapter with Django backend.
I'm having issue creating record when there's belongsTo and hasMany relationship going on.
I currently have this code:
App.Article = DS.Model.extend({
title: attr(),
description: attr(),
authors: hasMany('author'),
category: belongsTo('page'),
slug: attr(),
content: attr(),
articleContent: Ember.computed.alias("content"),
published: attr(),
publish_from: attr(),
isScheduled: function() {
return moment().isBefore(moment(this.get('publish_from')));
}.property('publish_from'),
articlePublishDate: function() {
return moment(this.get('publish_from')).format('MMMM Do YYYY');
}.property('publish_from'),
articlePublishTime: function() {
return moment(this.get('publish_from')).format('h:mm a');
}.property('publish_from'),
//content_type: belongsTo('content_type', { async: true }),
content_type: attr()
});
App.Page = DS.Model.extend({
title: attr(),
description: attr(),
pageContent: attr(null, {
key: 'content'
}),
templateFile: attr(null, {
key: 'template'
}),
slug: attr(),
tree_path: attr(),
tree_parent: belongsTo('page'),
site: attr()
});
App.Author = DS.Model.extend({
name: attr(),
slug: attr(),
description: attr(),
text: attr(),
email: attr(),
photo: attr(),
user: belongsTo('user'),
});
// create article
App.ArticleCreateController = Ember.ObjectController.extend({
editMode: false,
allAuthors: function() {
return this.store.find('author');
}.property(),
allPages: function() {
return this.store.find('page');
}.property(),
actions: {
save: function(session) {
var self = this;
var article = this.get('model');
var newArticle = this.store.createRecord('article', {
content_type: "19",
content: article.get('articleContent'),
description: article.get('description'),
publish_from: article.get('publish_from'),
published: article.get('published'),
slug: article.get('slug'),
title: article.get('title')
});
this.store.find('page', 3).then(function(page) {
newArticle.set('category', page);
});
newArticle.save();
}
}
});
All I really want to do is POST data like this to apiRoot/articles/ (along with other attributes, but those are working the way they should)
authors: [1,3,5], // hasMany
category: 3 // belongsTo
But when I make a POST request, category returns as null for some reason. All I want to extract from it is just the id itself. Also, I have no clue how to extract the array of authors. I tried posting the data, and it tells me something about it needing to be 'App.Author'.
First, at the current time you need a fork of ember-data because async create is currently broken (as it's a promise and the internal serializer won't wait for it to resolve).
Pull down this branch, do a npm install + grunt test to build the adapter. Also you need to use the forked build of ember-data in that branch'es test lib directory (until ember-data pulls in the fix for this)
https://github.com/toranb/ember-data-django-rest-adapter/tree/asyncBelongsToHasManyWIP
Then inside your controller you can do something like this to "create" the customer and appointment (notice -async belongsTo/hasMany relationship)
App.Customer = DS.Model.extend({
name: DS.attr('string'),
appointments: DS.hasMany('appointment', { async: true})
});
App.Appointment = DS.Model.extend({
details: DS.attr('string'),
customer: DS.belongsTo('customer', { async: true})
});
var customer = {
name: 'foobar'
}
this.store.createRecord('customer', customer).save().then(function(persisted) {
var appointment = {
details: 'test',
customer: persisted
}
return self.store.createRecord('appointment', appointment).save().then(function(apt) {
persisted.get('data').appointments.pushObject(apt);
router.transitionTo('index');
});
});

ember Uncaught Error: assertion failed: Emptying a view in the inBuffer state

I get this assertion when run the code below:
Emptying a view in the inBuffer state is not allowed and should not
happen under normal circumstances. Most likely there is a bug in your
application. This may be due to excessive property change
notifications.
Link to demo:
http://plnkr.co/edit/s3bUw4JFrJvsL690QUMi
var App = Ember.Application.create({
Store: DS.Store.extend({
revision: 4,
adapter: DS.FixtureAdapter.create()
}),
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router){
var person;
person = App.Person.find(657);
person.addObserver("isLoaded", function() {
return router.get('router.applicationController').connectOutlet("things", person.get("things"));
});
}
})
})
}),
ApplicationController: Em.Controller.extend(),
ApplicationView: Em.View.extend({
template: Em.Handlebars.compile("{{outlet}}")
}),
ThingsController: Em.ArrayController.extend({
thingTypes: (function() {
return App.ThingType.find();
}).property()
}),
ThingsView: Em.View.extend({
template: Em.Handlebars.compile([
'{{#each controller.thingTypes}}',
'{{this.name}}',
'{{/each}}',
'{{#each controller.content}}',
'{{this.title}}',
'{{/each}}'].join(""))
}),
//MODELS
Person: DS.Model.extend({
things: DS.hasMany('App.Thing', {
embedded: true
})
}),
Thing: DS.Model.extend({
description: DS.attr('string'),
thingType: DS.belongsTo("App.ThingType", {
embedded: true
}),
title: (function() {
return this.get("thingType.name");
}).property("description")
}),
ThingType: DS.Model.extend({
name: DS.attr("string")
})
});
App.Person.FIXTURES = [
{
id: 657,
things: [
{
id: 1,
description: "Some text",
thing_type: {
id: 1,
name: "type 1"
}
}, {
id: 2,
description: "Some text",
thing_type: {
id: 2,
name: "type 2"
}
}
]
}
];
App.ThingType.FIXTURES = [
{
id: 1,
name: "type 1"
}, {
id: 2,
name: "type 2"
}, {
id: 3,
name: "type 3"
}
];
Why is this happening?
I was having the same error while trying to load a list of dropdown values from fixtures. What resolved it was overriding queryFixtures on the fixture adapter:
App.FixtureAdapter = DS.FixtureAdapter.extend
latency: 200
queryFixtures: (records, query, type) ->
records.filter (record) ->
for key of query
continue unless query.hasOwnProperty(key)
value = query[key]
return false if record[key] isnt value
true
I probably wouldn't have figured it out had I not set the latency first. Then the error was a bit more descriptive.
a bit late I guess... but I got it to work here:
http://plnkr.co/edit/hDCT4Qy1h5aE6GjM76qp
Didn't change the logic but where its called
I modified your router like this:
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router) {
var person;
router.set('router.applicationController.currentPerson', App.Person.find(657));
}
})
})
})
And created an ApplicationController:
ApplicationController: Em.Controller.extend({
currentPerson: null,
currentPersonLoaded: function() {
this.connectOutlet("things", this.get("currentPerson.things"));
}.observes("currentPerson.isLoaded"),
})
I dont know if this is the output you wished but the bug vanished!