简体   繁体   中英

Ember, Ember-data and Rails relations error: “Cannot read property 'typeKey' of undefined”

I connect Ember to a Rails API which delivers some JSON.

I'm trying to get relations working ( product hasMany images ) but it keeps giving me this error:

Cannot read property 'typeKey' of undefined

My Models:

App.Product = DS.Model.extend({
  images: DS.hasMany('image'),
  title: DS.attr('string'),
});


App.Image = DS.Model.extend({
  product: DS.belongsTo('product')
});

Rails renders json as:

{
  "products":[
    {
      "id": 1,
      "title": "product title",
      "images":[
        {
          "id": 1,
          "urls":
          {
            "thumb":"http://domain.com/thumb/image.jpg",
            "original":"http://domain.com/original/image.jpg"
          }
        }
      ]
    }
  ]
}

Turns out I needed to "sideload" my images in Rails, so the JSON became:

{
  "products":[
    {
      "id": 1,
      "title": "product title",
      "image_ids": [1]
    }
  ],
  "images":[
    {
      "id": 1,
      "urls":
      {
        "thumb":"http://domain.com/thumb/image.jpg",
        "original":"http://domain.com/original/image.jpg"
      }
    }
  ]
}

Rails' ProductSerializer:

class ProductSerializer < ActiveModel::Serializer

  embed :ids, :include => true

  attributes :id, :title

  has_many :images

  methods :image_urls

end

It seems that you were using embedded JSON in your example. You need to use the EmbeddedRecordsMixin https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/embedded_records_mixin.js and set the appropriate flag to mark images as being embededd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM