使用Ember.js和Ember数据序列化传出数据
我正在使用Ember.js1.0.0和Ember-Data-beta2 我有一个属于公司的模型产品。创建产品时,用户可以在下拉菜单中选择它所属的公司。这将在表单帖子中添加company:25,这在很大程度上正是我想要的。但是,我希望表单提交公司id,而不是公司id。如何更改使用Ember.js和Ember数据序列化传出数据,ember.js,ember-data,Ember.js,Ember Data,我正在使用Ember.js1.0.0和Ember-Data-beta2 我有一个属于公司的模型产品。创建产品时,用户可以在下拉菜单中选择它所属的公司。这将在表单帖子中添加company:25,这在很大程度上正是我想要的。但是,我希望表单提交公司id,而不是公司id。如何更改 据我所知,Ember数据序列化程序只规范化传入数据,而不是传出数据。这会在适配器中处理吗?如果是这样,我如何将此约定传达给Ember?编辑:此解决方案已过时,请按照Panagiotis Panagi的建议使用ActiveMo
据我所知,Ember数据序列化程序只规范化传入数据,而不是传出数据。这会在适配器中处理吗?如果是这样,我如何将此约定传达给Ember?编辑:此解决方案已过时,请按照Panagiotis Panagi的建议使用ActiveModelAdapter 对于ember数据的最新版本,您必须重写序列化程序,以获得rails的freindly behavior。像这样:
// 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;
}
});
我希望这能有所帮助。使用ActiveModelAdapter请参见PR:
很高兴知道我的解决方案已经过时了。我刚刚成功地将代码更改为使用ActiveModelAdapter。太棒了!我无法告诉你我花了多少时间来让它工作。
App.ApplicationAdapter = DS.ActiveModelAdapter.extend();