如何在ember-model中使用belongsTo?

时间:2013-09-01 12:47:22

标签: ember.js handlebars.js ember-model

我使用ember-model创建了FIXTURES,但我无法在模板上使用以下节点

    "logged_in": {
        "id" : "1",
        "logged": true,
        "username": "sac1245",
        "account_id": "4214"
    } 

我已为此节点实施了belongsTo关系,但它引发了一个错误:Uncaught Error: Ember.Adapter must implement findQuery
这里我列出了我的模型代码:

Astcart.Application =  Ember.Model.extend({
    name: Ember.attr(),
    logo_url : Ember.attr(),
    list: Ember.hasMany('Astcart.List', {key: 'list', embedded: true}),
    logged_in: Ember.belongsTo('Astcart.Logged_in', {key: 'logged_in'})
});

    Astcart.List = Ember.Model.extend({
      name: Ember.attr()
    });

    Astcart.Logged_in = Ember.Model.extend({
      id: Ember.attr(),
      logged: Ember.attr(),
      username: Ember.attr(),
      account_id: Ember.attr()
    });

    Astcart.Application.adapter = Ember.FixtureAdapter.create();

    Astcart.Application.FIXTURES = [
        {
            "id"     : "1",
            "logo_url": "img/logo.jpg",
            "logged_in": {
                "id" : "1",
                "logged": true,
                "username": "sac1245",
                "account_id": "4214"
            },          
            "name": "gau",
            "list": [
                        {
                            "id"     : "1",
                            "name": "amit"
                        },
                        {
                            "id"     : "2",                 
                            "name": "amit1"
                        }
            ]
        }
    ];

模板代码:

    {{#each item in model}}
        {{item.name}}
        {{item.logged_in.logged}}                               
    {{/each}}

路由器代码:

  Astcart.ApplicationRoute = Ember.Route.extend({
    model: function() {
      return Astcart.Application.find();
    }
  }); 

任何人都可以告诉我如何访问模板中上述节点的数据吗?

1 个答案:

答案 0 :(得分:3)

您当前的灯具嵌入了logged_in数据:

Astcart.Application.FIXTURES=[
    {
        ...
        "logged_in": {
            "id": "1",
            "logged": true,
            "username": "sac1245",
            "account_id": "4214"
        },
        ...
    }
];

因此logged_in属性映射需要参数embedded: true才能找到此数据,如下所示:

Astcart.Application =  Ember.Model.extend({
  ...
  logged_in: Ember.belongsTo('Astcart.Logged_in', {key: 'logged_in', embedded: true })
});

如果没有这个,它会尝试查询Astcart.Logged_in

Astcart.Logged_in.find(1)

并且因为它没有适配器,将失败并出现例外:Uncaught Error: Ember.Adapter must implement findQuery

你可以看到这个工作在那个小提琴http://jsfiddle.net/marciojunior/8zjsh/