PDA

View Full Version : associations: no auto generated getters



bennyl
17 Feb 2012, 12:50 AM
Hi,
i tried to follow the documentation about association and build the following models


Ext.define('Soa.model.Post', {
extend: 'Ext.data.Model',

proxy: {
type: 'rest',
url : '/data/posts/',
reader: {
type: 'json',
root: 'posts'
}
},

fields: ["id", "title", "pubDate", "body", "posted"],


belongsTo: { model: 'Soa.model.User', name: 'author' }
});

Ext.define('Soa.model.User', {
extend: 'Ext.data.Model',

proxy: {
type: 'rest',
url : '/data/users/',
reader: {
type: 'json',
root: 'users'
}
},

fields: ["id", "name"],


hasMany: "Soa.model.Post"
});





then i load some posts for example by doing:



var posts = Ext.create('Ext.data.Store', {
model: 'Soa.model.Post'});
posts.load();
var p = posts.getAt(0);
console.log(p.getAuthor());


and the result is that p.getAuthor is not defined,
but if i call


console.log(p.data.body);

i received the correct data.

what am i doing wrong?

mitchellsimoens
17 Feb 2012, 4:53 AM
Does the response have an author field to get the belongsTo data?

bennyl
17 Feb 2012, 6:31 AM
yes - here is the response


{
"posts":[{
"posted":false,
"title":"this is the test title",
"author":{
"name":"user1",
"posts":[],
"id":1
},
"pubDate":"Feb 17, 2012 6:21:35 AM",
"body":"this is a test",
"id":1
}],
"success":true
}

mitchellsimoens
17 Feb 2012, 6:45 AM
You need to do the check after the store has loaded. Also, I added a couple things to the belongsTo to get it to work:


Ext.define('Soa.model.Post', {
extend: 'Ext.data.Model',

proxy: {
type: 'rest',
url : '/data/posts/',
reader: {
type: 'json',
root: 'posts'
}
},

fields: ["id", "title", "pubDate", "body", "posted"],

belongsTo: { model: 'Soa.model.User', name: 'author', associationKey : 'author', getterName : 'getAuthor' }
});

var posts = Ext.create('Ext.data.Store', {
model: 'Soa.model.Post'
});
posts.load(function(recs) {
var rec = recs[0];

console.log(rec);
console.log(rec.getAuthor());
});

bennyl
17 Feb 2012, 7:01 AM
thank you for your help,
that gotten me one step closer but,

when i do:


rec.getAuthor().get("name");

this is still undefined - the class name is indeed the "Soa.model.User" but this seem to be no data on it
so how do i get the user data?

mitchellsimoens
17 Feb 2012, 7:07 AM
Have you taken a look at what getAuthor returns?

bennyl
17 Feb 2012, 7:33 AM
yes,
i looked at the $className field and it value is "Soa.model.User" this why i expect it to have the user fields - like name and id - am i missing something?

mitchellsimoens
17 Feb 2012, 7:41 AM
Well that's odd. And the data has the name property?

bennyl
17 Feb 2012, 8:01 AM
rec.getAuthor().data is undefined
rec.getAuthor().name is : "" (the empty string)
and rec.getAuthor().getName() is "Soa.model.User"

strange...