Ember数据:更改belongsTo发送到服务器的父ID

时间:2015-11-11 19:31:47

标签: ember.js ember-data ember-cli

保存此模型:

  export default DS.Model.extend({
      type: DS.attr('string'),
      primary: DS.attr('boolean'),
      address: DS.attr('string'),
      address2: DS.attr('string'),
      city: DS.attr('string'),
      state: DS.attr('string'),
      postal: DS.attr('string'),
      customer: DS.belongsTo('customer')
   });

使用此路线:

   3 export default Ember.Route.extend({
   4   model() {
   5     return this.store.createRecord('customer-address', {
   6       customer: this.modelFor('customers/show')
   7     });
   8   },
   9   actions: {
  10     save() {
  11       var model = this.modelFor('customer-addresses/new');
  12       model.save().then(() => {
  13         this.transitionTo('customer-addresses');
  14       });
  15     },
  16     cancel() {
  17       this.transitionTo('customer-addresses');
  18     }
  19   }
  20 });

Params会像这样发送到我的后端:

Parameters: %{"customer_address" => %{"address" => nil, "address2" => nil, "city" => nil, "customer" => "23", "postal" => nil, "primary" => false, "state" => nil, "type" => ""}}

customer需要customer_id(la Rails),因为客户有很多customer_addresses。

更新:这是我的序列化程序

   1 import config from '../config/environment';
   2 import DS from 'ember-data';
   3 import Ember from 'ember';
   4
   5 var serializer;
   6 if (config.environment === 'test') {
   7   serializer = DS.JSONSerializer.extend({});
   8 } else {
   9   serializer = DS.RESTSerializer.extend({
  10     keyForAttribute: function(attr, method) {
  11       return Ember.String.underscore(attr);
  12     },
  13     payloadKeyFromModelName: function(modelName) {
  14       return Ember.String.underscore(modelName);
  15     },
  16   });
  17 }
  18
  19 export default serializer;

1 个答案:

答案 0 :(得分:1)

您应该覆盖序列化程序上的keyForRelationship(请参阅here)。

keyForRelationship: function(key, relationship, method) {
     return Ember.String.underscore(key) + '_id';
}

如果您正在使用Rails,我会查看Ember Data Active Model Adapter / Serializer,它已被提取到插件here中。