How to get errors on Ember hasMany (child) records submitted to API during Save

I have 2 models:

App.Grower = DS.Model.extend
  name: DS.attr('string')
  addresses: DS.hasMany('App.Address')

App.Address = DS.Model.extend(
  line_1: DS.attr("string")
  line_2: DS.attr("string")
  city: DS.attr("string")
  region: DS.attr("string")
  postalCode: DS.attr("string")

  grower: DS.belongsTo("App.Grower")
)

Because the Addresses records are embedded in the Grower records, on Update, when I save a Grower, the Address(es) also get saved with a simple call to model.save(), or transaction.commit().

I also have a handler in the Update code to handle a rejection from API due to validation issues:

...
model.on "becameInvalid", =>
  errors = []
  $.each model.errors, (key, value) ->
    errors += key + " : " + value + "<br>"
...

When I get a 422 from the API (which is Rails by the way), the json response also includes the invalid fields. For example:

{"errors":{"name":["can't be blank"]}}

and the "becameInvalid" snippet above handles this and spits out the model (Grower) errors.

However, if the errors are on the addresses , which come back like this:

{"errors":{"addresses.line_1":["can't be blank"]}}

they don't seem to be found under model (Grower) errors.

Where do I find them? I have tried model.get('addresses').errors , model.get('addresses').objectAt(0).errors , etc., but with no success.

UPDATE:

Taking a look at source, child relationship errors don't seem to be included when the errors object is built:

rest_adapter.js

...
didError: function(store, type, record, xhr) {
  if (xhr.status === 422) {
    var json = JSON.parse(xhr.responseText),
        serializer = get(this, 'serializer'),
        errors = serializer.extractValidationErrors(type, json);

    store.recordWasInvalid(record, errors);
  } else {
    this._super.apply(this, arguments);
  }
}
...

rest_serializer.js

...
extractValidationErrors: function(type, json) {
  var errors = {};

  get(type, 'attributes').forEach(function(name) {
    var key = this._keyForAttributeName(type, name);
    if (json['errors'].hasOwnProperty(key)) {
      errors[name] = json['errors'][key];
    }
  }, this);

  return errors;
}
...

Looks like only errors whose name matches an attribute on the parent model get returned.

The problem is, in this case of hasMany and embedded, the parent is the only model that seems to be invalidated, even though it's the child that may cause the validation error. This happens because the children get submitted to the back-end API's update action as attributes of the parent.

So why not include child errors in the parent model's errors collection? Or am I missing something?

UPDATE 2

I submitted an issue at the ember-data github repo here. Let's see what the bright minds over there have to say.

链接地址: http://www.djcxy.com/p/64076.html

上一篇: 保存从模态组件中呈现的表单中捕获的数据

下一篇: 如何在Ember上获取错误hasMany(子)记录在保存期间提交给API