PDA

View Full Version : nested response when theres no associated model



dedoz
13 Mar 2012, 1:25 PM
response when loading a record with nested associated model data looks like..
loading a person and a person who hates him :d


{ id : 5
name : 'peter'
hater : {
id : 2
name : 'alex'
hates_id : 5
}
}

(i know this is not valid json, mising quotes and stuff, is just an example)
this reperesent a peter hasOne hater, which is alex (associationKey: hater and foreignKey hates_id).

now if peter doesnt have a hater , there wont be data for associated record in the database.
so what should be the asnwer there so the getter doesnt try to load him again?


{ id : 5
name : 'peter'
hater : null ???? undefined ??
}

if i dont return the hater key, then getter doesnt know i already checked theres no associated record and tries to load it again.
if i use null then getter will try to load it again too, like i didnt returned the associationKey in the response.
if i use {} or [] then acts like the same as above

getter always ends creating a new empty record with an associated id set , but .. theres no associated record.
so how to work with getter, first to tell him theres no associated record and then how to work his asnwer ? to know there werent any associated record.

mitchellsimoens
14 Mar 2012, 9:52 AM
Maybe I am just slap happy today but your example is hilarious... No, peter will have a hater! :D

Ok, so the associations will always try to load. If you are always going to return data (not lazy load the data) then you can check if the associated data was saved as a property of the model. If the data is sent with the main model, it will create a model instance of the associated data and put that instance on the main model. You can technically skip using the getter and go for the property if you know the property name.