Skip to content

Instantly share code, notes, and snippets.

@hashg
Created July 24, 2013 17:25
Show Gist options
  • Save hashg/6072625 to your computer and use it in GitHub Desktop.
Save hashg/6072625 to your computer and use it in GitHub Desktop.
Ember Model : Person/Computers
var attr = Ember.attr, hasMany = Ember.hasMany, belongsTo = Ember.belongsTo;
var apiPrefix = '/api';
App.CustomAdapter = Ember.RESTAdapter.extend({
generateIdForRecord: function(record) {
var ch = "abcdefghiklmnopqrstuvwxyz"[Math.floor(25 * Math.random())];
return ch+'xxxyxxx'.replace(/[xy]/g, function(c) {
var r, v;
r = Math.random() * 16 | 0;
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
},
createRecord: function(record) {
console.log('custom : create');
record.set('id', this.generateIdForRecord());
return this._super(record);
},
buildURL: function() {
return this._super.apply(this, arguments).replace(/\.json$/, '');
}
});
App.Person = Ember.Model.extend({
id: attr(),
name: attr(),
computers: hasMany('App.Computer', {key: 'computers', embedded: true})
});
App.Person.url = apiPrefix + "/persons";
App.Person.rootKey = "";
App.Person.adapter = App.CustomAdapter.create();
App.Computer = Ember.Model.extend({
id: attr(),
name: attr(),
vendor: attr(),
person: belongsTo('App.Person', {key: 'person_id'})
});
App.Computer.url = apiPrefix + "/computers";
App.Computer.adapter = App.CustomAdapter.create();
/*
var newPerson = App.Person.create({"name":"name03"});
newPerson.save()
var comp = newPerson.get('computers')
comp.create({"name":"comp01", "vendor":"Apple", "person" : newPerson.get("id") });
comp.save()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment