I use JSONAPI as the adapter.
Model:
App.Report = DS.Model.extend({
'name': DS.attr('string'),
'description': DS.attr(),
'placemark': DS.belongsTo('placemark', {
'async': true
})
});
App.Placemark = DS.Model.extend({
'geometry': DS.attr(),
'description': DS.attr(),
'reports': DS.hasMany('report', {
'async': true
})
});
Route:
App.ReportRoute = Ember.Route.extend({
'model': function (params) {
return this.store.find('report', params.report_id);
},
'renderTemplate': function () {
this.render('report', {
'into': 'application'
});
}
});
App.PlacemarkRoute = Ember.Route.extend({
'model': function (params) {
return this.store.find('placemark', params.element_id);
},
'renderTemplate': function () {
this.render('placemark', {
'into': 'application'
});
}
});
i use a component for embeddeding a map canvas where the data (placemark) are come from the Report:
{{map-canvas placemark=model.placemark}}
App.MapCanvasComponent = Ember.Component.extend({
'availablePlacemark': Ember.computed('placemark', function() {
return this.get('placemark.geometry');
});
I found placemark is unable to retrieve and 'undefined' returned.
I tries using:
return this.get('placemark').then(function(placemark) {
return placemark.get('geometry');
});
it did not work.
now, I am thinking if it is a JSONAPI adapter issue or async problem from view to a components.
i am using ember 1.13
Hope someone could help
thanks
Related
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?
I'm updating a model using the following controller:
payment_controller.js
App.PaymentNewController = Ember.ObjectController.extend({
needs: ['student'],
isNew: true,
actions: {
createPayment: function() {
var date = new Date(this.get('date'));
if (!date) { return false; }
var amount = this.get('amount');
if (!amount) { return false; }
var studentId = this.get('controllers.student.id');
if (this.isNew)
{
var payment = this.store.createRecord('payment', {
date: date,
amount: amount,
});
}
else
{
var payment = this.get('model');
payment.set('date', date);
payment.set('amount', amount);
}
var self = this;
var onSuccess = function(payment) {
self.set('date', '');
self.set('amount', '');
self.transitionToRoute('student', studentId);
};
var onFail = function(payment) {
};
if (this.isNew)
{
this.store.find('student', studentId).then(function(student){
payment.set('student', student);
payment.save().then(onSuccess, onFail);
});
}
else
{
payment.save().then(onSuccess, onFail);
}
},
}
});
The data returned from the server is the following, and it looks in the correct format expected by ember:
{"payment":{"amount":1111,"date":"2014-09-09T00:00:00.000Z","student":"54024bb9cd52254e181325af","_id":"54024bdacd52254e181325b0"}}
The issue is that after saving the data is correctly saved to the database, but in the store is empty (UPDATE: except the id). As soon as I reload the page the data is shown correctly and is the updated version of the model. This made me think to the fact that the error could lie in the response of the PUT request, but it looks fine to me.
I've been trying many different things with no success. I can provide additional code or info if needed.
UPDATE 1
Here are the involved routes:
App.StudentsRoute = Ember.Route.extend({
model: function() {
return this.store.find('student');
}
});
App.StudentRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('student', params.student_id);
}
});
App.StudentEditRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controllerFor('student.new').setProperties({isNew:false, content:model});
},
renderTemplate: function() {
this.render('student/new');
}
});
App.PaymentNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('payment');
}
});
App.PaymentEditRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controllerFor('payment.new').setProperties({isNew:false, content:model});
},
renderTemplate: function() {
this.render('payment/new');
}
});
UPDATE 2
Here are the serializer and the adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:3000',
});
App.ApplicationSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: '_id',
serializeId: function(id) {
return id.toString();
},
attrs: {
payments: {embedded: 'always'},
lessons: {embedded: 'always'}
}
});
UPDATE 3
Here are the models:
App.Student = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
email: DS.attr('string'),
nationality: DS.attr('string'),
dateOfBirth: DS.attr('date'),
payments: DS.hasMany('payment'),
lessons: DS.hasMany('lesson'),
});
App.Payment = DS.Model.extend({
student: DS.belongsTo('student'),
date: DS.attr('date'),
amount: DS.attr('number'),
});
UPDATE 4
While inspecting the store using the Ember Inspector in Chrome I've noticed that after the update is completed, the only property that contains data in the payment object (in the store) is the id. Both date and amount are empty.
I have set up the following scaffolding for my Ember application.
window.App = Ember.Application.create({});
App.Router.map(function () {
this.resource('coaches', function() {
this.resource('coach', {path: "/:person_id"});
});
});
App.ApplicationAdapter = DS.FixtureAdapter.extend({});
App.Person = DS.Model.extend({
fname: DS.attr('string')
,lname: DS.attr('string')
,sport: DS.attr('string')
,bio: DS.attr('string')
,coach: DS.attr('boolean')
,athlete: DS.attr('boolean')
});
App.Person.FIXTURES = [
{
id: 10
,fname: 'Jonny'
,lname: 'Batman'
,sport: 'Couch Luge'
,bio: 'Blah, blah, blah'
,coach: true
,athlete: true
}
,{
id: 11
,fname: 'Jimmy'
,lname: 'Falcon'
,sport: 'Cycling'
,bio: 'Yada, yada, yada'
,coach: false
,athlete: true
}
];
I am trying to set up a route to filter the person model and return only coaches. Just to make sure I can access the data, I have simply used a findAll on the person model.
App.CoachesRoute = Ember.Route.extend({
model: function() {
return this.store.findAll('person');
}
});
Now though, I am trying to implement the filter method detailed on the bottom of the Ember.js Models - FAQ page.
App.CoachesRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return store.filter('coaches', { coach: true }, function(coaches) {
return coaches.get('isCoach');
});
}
});
The coaches route is not working at all with the new route implemented and the old one commented out. I am using the Ember Chrome extension and when using the filter route the console responds with, Error while loading route: Error: No model was found for 'coaches'. Apparently the route is not working, specifically the model. No kidding, right? What am I missing in my filter model route?
Thank you in advance for your help.
The error message is spot on- there is no CoachModel. I think you need to do this:
App.CoachesRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return store.filter('person', { coach: true }, function(coaches) {
return coaches.get('isCoach');
});
}
});
What I have done -
Model -
App.Book = DS.Model.extend({
book_name: DS.attr('string'),
edition: DS.attr('string')
});
Router -
App.Router.map(function() {
this.resource('books', function() {
this.route('new');
});
});
App.BooksNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('book');
},
actions: {
save: function() {
this.modelFor('newBook').save();
}
}
});
Now Can anybody help me.. How to save data ?
I am getting error like
TypeError: this.modelFor(...) is undefined
this.modelFor('newBook').save();
It is hard to tell how the context of your action looks like.
But one option is to pass the object you want to save as a parameter like this {{action save myBook}}.
Then you action could look like this:
App.BooksNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('book');
},
actions: {
save: function(book) {
book.save();
}
}
});
I think this should work.
App.BooksNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('book');
},
actions: {
save: function() {
this.get('model').save();
}
}
});
Given the following Ember.js application (using Ember 1.0.0.rc.6.1 and Ember Data 0.13):
App = Ember.Application.create({ LOG_TRANSITIONS: true });
App.Store = DS.Store.extend();
App.Router.map(function() {
this.resource('promotions', function() {
this.resource('promotion', { path: '/:promotion_id' }, function() {
this.resource('entrants', function() {
this.resource('entrant', { path: '/:entrant_id' });
});
});
});
});
App.PromotionRoute = Ember.Route.extend({
model: function() {
return { id: 1, name: 'My Promotion' };
}
});
App.EntrantsIndexRoute = Ember.Route.extend({
model: function(params) {
console.warn('EntrantsIndexRoute', '\nparams:', params, '\nparams.promotion_id:', params.promotion_id, '\narguments:', arguments);
console.log('params should be:', { promotion_id: 1 });
console.log('The queried URL should be:', '/entrants?promotion_id=1');
return App.Entrant.find({promotion_id: params.promotion_id});
}
});
App.Entrant = DS.Model.extend({
name: DS.attr('string')
});
If you enter the url #/promotions/1/entrants, which should be a nested resource, the params is an empty object. How can I access promotion_id there? JSFiddle here, take a look at the console after clicking on "Click me": http://jsfiddle.net/Kerrick/4GufZ/
While you can't access the dynamic segments of the parent route, you still can retrieve the model for the parent route and get its ID, like this:
App.EntrantsIndexRoute = Ember.Route.extend({
model: function() {
var promotion_id = this.modelFor('promotion').id;
return App.Entrant.find({ promotion_id: promotion_id });
}
});
Or, if there is a has-many relation between promotion and entrants, you even might do:
App.EntrantsIndexRoute = Ember.Route.extend({
model: function() {
return this.modelFor('promotion').get('entrants');
}
});
Try this code:
App.EntrantsIndexRoute = Ember.Route.extend({
model: function() {
var promotion_id = this.modelFor('promotion').query.promotion_id;
return App.Entrant.find({ promotion_id: promotion_id });
}
});