编辑:此解决方案已过时,请改用 ActiveModelAdapter,如 Panagiotis Panagi 所建议的那样。
使用最新版本的 ember-data,您必须重写序列化程序,才能获得“rails freindly behaivor”。像这样:
// See https://github.com/emberjs/data/blob/master/TRANSITION.md
// and http://discuss.emberjs.com/t/changes-with-ds-restadapter/2406/8
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalize: function(type, hash, property) {
var normalized = {}, normalizedProp;
for (var prop in hash) {
if (prop.substr(-3) === '_id') {
// belongsTo relationships
normalizedProp = prop.slice(0, -3);
} else if (prop.substr(-4) === '_ids') {
// hasMany relationship
normalizedProp = Ember.String.pluralize(prop.slice(0, -4));
} else {
// regualarAttribute
normalizedProp = prop;
}
normalizedProp = Ember.String.camelize(normalizedProp);
normalized[normalizedProp] = hash[prop];
}
return this._super(type, normalized, property);
},
serialize: function(record, options) {
json = {}
record.eachAttribute(function(name) {
json[name.underscore()] = record.get(name)
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind == 'hasMany') {
key = name.singularize().underscore() + '_ids'
json[key] = record.get(name).mapBy('id')
} else {
key = name.underscore() + '_id'
json[key] = record.get(name + '.id')
}
});
if (options && options.includeId) {
json.id = record.get('id')
}
return json
},
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
},
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
},
serializeAttribute: function(record, json, key, attribute) {
var attrs = Ember.get(this, 'attrs');
var value = Ember.get(record, key), type = attribute.type;
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
key = attrs && attrs[key] || Ember.String.decamelize(key);
json[key] = value;
}
});
我希望这有帮助。