【问题标题】:Ember, Ember-data and Rails relations error: "Cannot read property 'typeKey' of undefined"Ember、Ember-data 和 Rails 关系错误:“无法读取未定义的属性 'typeKey'”
【发布时间】:2014-08-11 16:11:08
【问题描述】:

我将 Ember 连接到提供一些 JSON 的 Rails API。

我正在尝试让关系正常工作 (product hasMany images),但它一直给我这个错误:

Cannot read property 'typeKey' of undefined

我的模特:

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


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

Rails 将 json 呈现为:

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

【问题讨论】:

    标签: ruby-on-rails ember.js ember-data


    【解决方案1】:

    原来我需要在 Rails 中“侧载”我的图像,所以 JSON 变成了:

    {
      "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
    

    【讨论】:

      【解决方案2】:

      您的示例中似乎使用了嵌入式 JSON。您需要使用 EmbeddedRecordsMixin https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/embedded_records_mixin.js 并设置适当的标志以将 images 标记为嵌入

      【讨论】:

      • 感谢您的回复!我尝试将{embedded: 'always'} 添加为hasMany 的第二个参数,但没有成功。可能是因为我需要这个 Mixin 吗?我现在让 Rails 使用侧载图像渲染 JSON,效果很好。请参阅下面的答案。
      • 是的,您需要使用 EmbeddedRecordsMixin 才能使 {embedded: 'always'} 工作
      • 感谢 Igor,虽然您的回答是正确的 (+1),但我将自己的回答标记为已接受,因为 ember 建议侧载关系。 emberjs.com/guides/models/the-rest-adapter
      猜你喜欢
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多