3
App.CardCategory = DS.Model.extend
  properties: DS.hasMany 'App.CardProperty'

App.CardProperty = DS.Model.extend
  symbol: DS.attr 'string'
  label: DS.attr 'string'
  popover: DS.attr 'string'
  unit: DS.attr 'string'

DS.RESTAdapter.configure 'plurals',
  card_property: 'card_properties'

我可以通过 App.XXX.find() / find(n) 获得两者CardPropertyCardCategory但无法在 Chrome 控制台中遍历这种关系。

这个:

App.CardCategory.find(1).get('properties').objectAt(1)

返回“未定义”,而:

App.CardCategory.find(1).get('properties')

返回:

Class {type: undefined, store: Class, _changesToSync: Ember.OrderedSet, owner: Class, name: "properties"…}

我总是在控制台中获取数据时遇到问题,所以我想知道这样做的最终方法是什么。


更新

回应评论。

App.CardCategory.find(1).get('properties.length') returns0 . The response to/card_categories/1`如下:

{
  "card_category":{
    "contains_new_purchase_slider":false,
    "id":1,
    "name":"Balance Transfer Cards",
    "promo_card_id":3,
    "promo_panel_active":true,
    "promo_panel_card_teaser":"Maiores rerum quibusdam consectetur id culpa. Enim unde explicabo et quae",
    "promo_panel_description":"Fugiat optio sint dolores non ut qui eveniet.",
    "promo_panel_header":"Unde ut voluptates eos ea dolor rerum mollitia.",
    "property_ids":[
      4,
      2,
      5,
      16
    ],
    "slug":"balance-transfer-cards"
  }
}
4

2 回答 2

2

一些快速的细节,hasMany 和 belongsTo 在找到后不会立即实现。

尝试几件事,看看是否是这种情况。

App.CardProperty.find(); // load the properties first
var cc = App.CardCategory.find(1);
var props = cc.get('properties');
propsLength = props.get('length');
props.forEach(function(prop){
   console.log('prop exists here: ' + prop.get('label'));
}

如果是这种情况,你总是可以做

Ember.run.next({
   // they will be materialized at this point
});
于 2013-07-28T22:19:23.617 回答
1

好的,我终于想通了。首先,CardCategory应该有cardPropertieskey 并且 JSON 中的 key 应该命名为card_property_ids。我想我不能使用properties' because the model is namedApp.CardProperty`。所以 unline 其他模型字段,关系应该以模型名称命名。这是正确的例子:

App.CardCategory = DS.Model.extend
  cardProperties: DS.hasMany 'App.CardProperty'

App.CardProperty = DS.Model.extend
  symbol: DS.attr 'string'
  label: DS.attr 'string'
  popover: DS.attr 'string'
  unit: DS.attr 'string'

DS.RESTAdapter.configure 'plurals',
  card_property: 'card_properties'

{
  "card_category":{
    "contains_new_purchase_slider":false,
    "id":1,
    "name":"Balance Transfer Cards",
    "promo_card_id":3,
    "promo_panel_active":true,
    "promo_panel_card_teaser":"Maiores rerum quibusdam consectetur id culpa. Enim unde explicabo et quae",
    "promo_panel_description":"Fugiat optio sint dolores non ut qui eveniet.",
    "promo_panel_header":"Unde ut voluptates eos ea dolor rerum mollitia.",
    "card_property_ids":[
      4,
      2,
      5,
      16
    ],
    "slug":"balance-transfer-cards"
  }
}
于 2013-07-30T17:39:36.770 回答