Ember-data: validation errors on relationships (hasMany)

时间:2016-04-04 16:53:28

标签: ember.js ember-data has-many validationerror

I'm trying to create record with associated records in one request. In case if some of nested records have validation errors, I'd like to access appropriate errors on that record. I'm using json-api adaptor, so what should be the format of errors from the backend? I'm trying something like this, with no luck though:

{"errors":[
  {
    "detail": "can't be blank",
    "source": {
      "pointer":"data/relationships/steps/0/data/attributes/est_threshold"
    }
  }
]}

According to this line, it should be implemented somehow: https://github.com/emberjs/data/blob/master/addon/adapters/errors.js#L7

Any ideas?

2 个答案:

答案 0 :(得分:0)

You'll need to sideload nested records in the data. The example structure given in the ember guides is:

{
  "post": {
    "id": 1,
    "title": "Node is not omakase",
    "comments": [1, 2, 3]
  },

  "comments": [{
    "id": 1,
    "body": "But is it _lightweight_ omakase?"
  },
  {
    "id": 2,
    "body": "I for one welcome our new omakase overlords"
  },
  {
    "id": 3,
    "body": "Put me on the fast track to a delicious dinner"
  }]
}

https://guides.emberjs.com/v1.10.0/models/the-rest-adapter/

答案 1 :(得分:0)

所以它似乎还没有实现。我在模型mixin中找到了一种hackish方式:

`import Ember from 'ember'`

RelatedErrors = Ember.Mixin.create

  save: ->
    @_super().catch (resp) =>
      resp.errors.forEach (err) =>
        if [_, rel, idx, attr] = err.source.pointer.match /^data\/relationships\/(\w+)\/(\d+)\/data\/attributes\/(\w+)$/
          @get(rel).objectAt(idx).get('errors').add(attr, err.detail)

`export default RelatedErrors`

但是,不推荐使用DS.Errors上的add,因此这仍然不是一个完美的解决方案。在每次提交之前,还需要清除相关模型的无效状态,这种情况到目前为止还没有发生。