Tim Baas
Tim Baas

Reputation: 6185

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"
          }
        }
      ]
    }
  ]
}

Upvotes: 1

Views: 178

Answers (2)

Tim Baas
Tim Baas

Reputation: 6185

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

Upvotes: 2

IgorT
IgorT

Reputation: 348

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

Upvotes: 1

Related Questions