serialize underscored property ember-data - javascript

My serialzer works fine, exept for underscored properties. The sctucture of the JSON from server is:
var services = {
services:[{
id:8,
name:"Codin'",
service_category:{
id:5,
iso_code:"BDT",
prop:"Ohmmmm"
}
},
{
id:7,
name:"PR",
service_category:{
id:2,
iso_code:"SFD",
prop:"Naraya"
}
}]
};
after serialisation the payload looks like this:
var services = {
services:[{
id:8,
name:"Codin'",
service_category:5
},
{
id:7,
name:"PR",
service_category:2
}],
serviceCategories:[{
id:5,
iso_code:"BDT",
prop:"Ohmmmm"
},
{
id:2,
iso_code:"SFD",
prop:"Naraya"
}
]
};
But it in the template i cant access serviceCategory's prop
The models
App.Service = DS.Model.extend({
name: DS.attr('string'),
serviceCategory: DS.belongsTo('serviceCategory')
});
App.ServiceCategory = DS.Model.extend({
iso_code: DS.attr('string'),
prop:DS.attr()
});
Here is the JsBin as usual: http://jsbin.com/OxIDiVU/565

Your json has service_category as the property name in the service.
Easy fix is:
App.Service = DS.Model.extend({
name: DS.attr('string'),
service_category: DS.belongsTo('serviceCategory')
});
and
<td>{{item.service_category.prop}} </td>
http://jsbin.com/OxIDiVU/570/edit

Related

Ember Data Polymorphic Relationship: Not Using Correct Model

Using an older version of ember(1.7.1) and ember-data(1.0.0 beta 12) as trying to upgrade to 2.0. When loading my application I get the following warning:
WARNING: The payload for 'App.QPAC' contains these unknown keys: [abs_parent_gbid,author,comments,course,follows,has_more_comments,is_announcement,more_comments_count,resource_uri,title]. Make sure they've been defined in your model.
Here is my model code (There are other models than post but they aren't being loaded in this instance).
App.Feedstory = DS.Model.extend({
global_id: DS.attr('string'),
story_type: DS.attr('string'),
story: DS.belongsTo('qPAC', {polymorphic: true}),
});
App.QPAC = DS.Model.extend({
global_id: DS.attr('string'),
global_code: DS.attr('string'),
body: DS.attr('string'),
});
App.Post = App.QPAC.extend({
title: DS.attr('string'),
is_announcement: DS.attr('boolean'),
author: DS.belongsTo('user'),
comments: DS.hasMany('comment'),
});
Ember inspector is showing me that the all the feedstory objects of type Post are being found and it shows in the Post attributes that the correct IDs are being loaded but not the other attributes.
The warning says it's looking for the post attributes in the App.QPAC model and not App.Post. Any ideas?
Edit: Added serializers and adapters
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api/v2'
});
App.FeedstorySerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: 'global_id',
attrs: {
pin: {embedded: 'always' },
story: {embedded: 'always'},
},
});
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: 'global_id',
attrs: {
author: {embedded: 'always' },
course: {embedded: 'always' },
pin: {embedded: 'always' },
comments: {embedded: 'always'},
follows: {embedded: 'always'},
},
normalize: function(type, hash, prop) {
if (Object.keys(hash.comments).length === 0) {
hash.comments = null;
}
if (Object.keys(hash.follows).length === 0) {
hash.follows = null;
}
return this._super(type, hash, prop);
},
});

emberJS does not display model data

I am using emberJS to display data obtained from REST API. My ember app connects to REST server and server returns the JSON data, but when I try to display id of my restaurant in the template I get this output:
Restaurant id is:
Here are my models:
import DS from 'ember-data';
//restaurant.js model
export default DS.Model.extend({
restaurantId: DS.attr('int'),
name: DS.attr('string'),
rating: DS.attr('double'),
phone: DS.attr('double'),
reservationPrice: DS.attr('double'),
workingHours: DS.attr('string'),
deals: DS.attr('string'),
image: DS.attr('string'),
//Relations
coordinates: DS.belongsTo('coordinates'),
address: DS.belongsTo('address')
});
//coordinates.js model
import DS from 'ember-data';
export default DS.Model.extend({
latitude: DS.attr("double"),
longitude: DS.attr("double"),
//Relations
restaurant: DS.belongsTo('restaurant')
});
//address.js model
import DS from 'ember-data';
export default DS.Model.extend({
streetName: DS.attr("string"),
city: DS.attr("string"),
country: DS.attr("string"),
//Relations
restaurant: DS.belongsTo('restaurant')
});
my template:
Restaurant id is: <br>
{{restaurant.restaurantId}}
<br>
{{model.restaurantId}}
{{#each model as |restaurant|}}
<h2>{{restaurant.image}}</h2>
{{/each}}
and my route:
//restaurant.js route
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.findAll('restaurant');
}
});
and of course, my serializer:
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeFindAllResponse(store, type, payload){
return {
id: "restaurantId",
data: {
type: type.modelName,
id: "restaurantId",
attributes: {
id: "restaurantId",
restaurantId: payload.restaurantId,
name: payload.name,
address: payload.address,
phone: payload.phone,
workingHours: payload.workingHours,
rating: payload.rating,
image: payload.image
}
}
};
}
});
Here is the JSON I get from server:
[ {
"restaurantId" : 1,
"name" : "Some name",
"address" : {
"streetName" : "some street",
"city" : "some town",
"country" : "some country"
},
"phone" : 984894,
"workingHours" : "08:00 - 23:00",
"rating" : 3.0,
"image" : "www.somelink.com"
},
...
]
I can see in Chrome inspector that my ember App makes a request to server and server responds with JSON. And there are no errors nor warnings, but my model data just does not get displayed. Any help is appreciated.
edit:
I wrote this normalizeFindRecord in my serializer, and now it looks like this:
normalizeFindRecordResponse(store, type, payload){
return {
data: {
type: type.modelName,
id: "restaurantId",
address: DS.belongsTo('restaurant', {embedded: true} ),
attributes: {
restaurantId: payload.restaurantId,
name: payload.name,
address: payload.address,
phone: payload.phone,
workingHours: payload.workingHours,
rating: payload.rating,
image: payload.image,
coordinates: payload.coordinates
}
}
};
}
and now when I try route this.store.findRecord('restaurant', 1); I get
Restaurant id is:
1
but the findAllRoute does still not work.

Ember Fixtures data not loading

I have been trying to get Ember fixtures data working on a test app I am developing that's based on the ember-rails gem. The data model seems to be loading when I use the Chrome Ember inspector tool but it doesn't load the actual data.
I have the following setup.
router.js
App.Router.map(function() {
this.resource('projects'), { path: '/' };
});
store.js
App.ApplicationAdapter = DS.FixtureAdapter
models/project.js
App.Project = DS.Model.extend({
name: DS.attr('string')
});
App.Project.FIXTURES = [
{ id: 1,
name: 'Test data 1'
},
{ id: 2,
name: 'Test data 2'
}
];
routes/projectsRoute.js
App.ProjectRoute = Ember.Route.extend({
model: function() {
return this.store.find('project');
}
});
As i mentioned this is built on top of rails using the ember-rails gem.
Any help would be much appreciated :)
Instead of adding FIXTURES as a key, it looks like you have to reopen the Model:
App.Project.reopenClass({
FIXTURES: [
{ id: 1,
name: 'Test data 1'
},
{ id: 2,
name: 'Test data 2'
}
]
});
http://emberjs.com/guides/models/the-fixture-adapter/

Ember Data - Assign a value inside an object

I'm starting up with ember and trying to get some data from an Api and assign it to an Emberjs model.
My api returns something like:
[
{
email: 'someemail#domain.com'
name: {
firstname: 'first name',
lastname: 'last name'
}
}
{
email: 'someemail2#domain.com'
name: {
firstname: 'another first name',
lastname: 'another last name'
}
},
{
email: 'someemail3#domain.com'
name: undefined
}
]
And my code is:
App.Store = DS.Store.extend({
revision: 12,
});
App.Store.registerAdapter('App.Users', DS.Adapter.extend({
findAll: function(store, type, id) {
$.getJSON('https://domain.com/users?callback=?', {
'auth_token': token
}).done(function(json){
store.loadMany(type, json);
});
},
}));
App.Store.registerAdapter('App.Users', DS.Adapter.extend({
findAll: function(store, type, id) {
$.getJSON('https://domain.com/users?callback=?', {
'auth_token': token
}).done(function(json){
store.loadMany(type, json);
});
},
}));
App.Router.map(function() {
this.route("users", { path: "/users" });
});
App.UsersRoute = Ember.Route.extend({
model: function() {
return App.Users.find();
}
});
App.Users = DS.Model.extend({
email: DS.attr('string'),
firstname: DS.attr('string'),
didLoad: function() {
console.log('model loaded', this.toJSON());
}
});
<script type="text/x-handlebars" data-template-name="users">
{{#each model}}
{{email}} - {{firstname}}
{{/each}}
</script>
Obviously firstname is empty for every object in the array.
Does anyone know what's the proper way to do this?
Thanks
Have you tried setting up your User model like this:
App.Adapter.map('App.User', {
name: {embedded: 'always'}
});
App.User = DS.Model.extend({
email: DS.attr('string'),
name: DS.belongsTo('App.UserName')
});
App.UserName = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string')
});

Load JSON in Ext store, associations missing

I'm using Ext 4.1. I have some issues with loading json data with associations. The flat data gets loaded perfectly, only the 'hasMany' doesn't work. (if loaded there nowhere to be found). If a record is loaded I want to be able to get the 2 stores of Attendee's and the 1 store of documents.
I can also change the JSON format to a better format (if you have suggestions let me know!)
I have this json data.
This is my first model:
Ext.define('App.model.package.LabVisit', {
extend: 'Ext.data.Model',
requires: [
'App.model.package.Attendee',
'App.model.package.Document'
],
idProperty: 'labVisitID',
fields: [
{
mapping: 'lab_visit_id',
name: 'labVisitID',
type: 'int'
},
{
mapping: 'lab_id',
name: 'labID',
type: 'int'
},
... some more irrelevant...
{
mapping: 'comments',
name: 'comments'
},
{
name: 'upddate'
}
],
hasMany: [
/* edit: added foreignKey (also tried with: lab_visit_id) */
{ model: 'package.Attendee', name: 'attendeeLabList', associationKey:'attendee_lab', foreignKey: 'labVisitId' },
{ model: 'package.Attendee', name: 'attendeeEmpList', associationKey:'attendee_emp', foreignKey: 'labVisitId' }
{ model: 'package.Document', name: 'document', associationKey:'document' },
]
});
I have following attendee model:
Ext.define('App.model.package.Attendee', {
extend: 'Ext.data.Model',
fields: [
/* edit: added this field */
{
mapping: 'lab_visit_id',
name: 'labVisitId'
},
{
mapping: 'attendee_id',
name: 'AttendeeID'
},
{
mapping: 'first_name',
name: 'firstName'
},
{
mapping: 'last_name',
name: 'lastName'
},
{
name: 'email'
}
]
});
following document model:
Ext.define('App.model.package.Document', {
extend: 'Ext.data.Model',
fields: [
{
mapping: 'document_id',
name: 'docID'
},
{
mapping: 'document_name',
name: 'docName'
},
{
mapping: 'document_mimetype',
name: 'mimeType'
},
{
name: 'uploadID'
}
]
});
Finally my store:
Ext.define('App.store.package.LabVisit', {
extend: 'Ext.data.JsonStore',
requires: [
'App.model.package.LabVisit'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.merge({
storeId: 'labVisitStore',
model: 'App.model.package.LabVisit',
remoteSort: true,
proxy: {
type: 'ajax',
api: {
read: API_URLS.getVisitList //url to the json
},
reader: {
type: 'json',
root: 'rows'
}
}
}, cfg)]);
}
});
Edit:
I've added the foreign key in the model and added it to the hasMany
Still no difference. This is my output:
I also find it a strange: If it's broken I expect an exception. And there are 2 mysterious stores always present but I don't have a clue why or what's the purpose.
The problem was in this part:
hasMany: [
{ model: 'package.Attendee', name: 'attendeeLabList', associationKey:'attendee_lab' },
{ model: 'package.Attendee', name: 'attendeeEmpList', associationKey:'attendee_emp' },
{ model: 'package.Document', name: 'document', associationKey:'document' },
]
#Izhaki helped me a lot. Thanx! Especially with the fiddle. I started there and begun with switching the code with my code piece by piece. Until I saw the model was the problem.
models should be defined like this: App.model.package.Attendee
I think it's sad that the framework doesn't show a significant error/warning if a model isn't recognised/doesn't excist/isn't supplied... But meh, it works now.

Categories