Skip to content

Instantly share code, notes, and snippets.

@ColinCampbell
Created February 13, 2010 20:32
Show Gist options
  • Save ColinCampbell/303662 to your computer and use it in GitHub Desktop.
Save ColinCampbell/303662 to your computer and use it in GitHub Desktop.
sc_require('models/record');
App.Customer = App.Record.extend({
/**
Walk like a duck
@property {Boolean}
@default YES
@isReadOnly
*/
isAppCustomer: YES,
phoneNumbers: SC.Record.toMany('App.PhoneNumber', {inverse: 'customer', isMaster: YES})
}) ;
// Creation of a record
var customerId = 123;
var phoneNumber = App.store.createRecord(App.PhoneNumber, {
customer: customerId
/* ... */
});
sc_require('models/record');
App.PhoneNumber = App.Record.extend({
/**
Walk like a duck
@property {Boolean}
*/
isAppPhoneNumber: YES,
customer: SC.Record.toOne('App.Customer', {inverse: 'phoneNumbers', isMaster: NO}),
/** @private
Needed because one-to-many relationships aren't enforced yet
*/
customerHasChanged: function() {
this.toOneHasChanged('customer');
}.observes('customer'),
destroy: function() {
this.destroyToOne('customer');
sc_super();
}
}) ;
/**
This is the parent record that other records for this app will inherit from
*/
App.Record = SC.Record.extend({
/**
Walk like a duck
@property {Boolean}
@default YES
@isReadOnly
*/
isAppRecord: YES,
/** @private
Needed because one-to-many relationships aren't enforced yet
@param {String} key The key of the toOne property
@returns {void}
*/
toOneHasChanged: function(key) {
var rec = this.get(key),
attribute = this[key],
inverse = attribute.get('inverse'),
type = attribute.get('typeClass');
if (!SC.none(attribute) && !SC.none(inverse) && !SC.none(type) && !SC.none(rec)) {
if (!rec.isAppRecord) {
rec = App.store.find(type, rec);
}
if (rec && rec.get(inverse)) {
rec.get(inverse).addInverseRecord(this);
}
}
},
/** @private
Needed because one-to-many relationships aren't enforced yet
@param {String} key The key of the toOne property
@returns {void}
*/
destroyToOne: function(key) {
var rec = this.get(key),
attribute = this[key],
inverse = attribute.get('inverse'),
type = attribute.get('typeClass');
if (!SC.none(attribute) && !SC.none(inverse) && !SC.none(type) && !SC.none(rec)) {
if (!rec.isAppRecord) {
rec = App.store.find(type, rec);
}
if (rec && rec.get(inverse)) {
rec.get(inverse).removeInverseRecord(this);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment