如何显示hasMany关联

时间:2015-06-22 12:05:48

标签: javascript ember.js

我是ember的新手,我创建了一个这样的模型:

# app/models/skill.js
export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  link: DS.attr('string'),
  user: DS.hasMany('user')
});

我有这条路线:

# app/routes/skill.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('skill', params.id);
  }
});

此路由器:

# app/router.js
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.resource('users', function() {
    this.route('index', { path: '/'} );
    this.route('signup');
  });
  this.resource('skills', function() {
    this.route('index', { path: '/' });
  });
  this.resource('skill', { path: '/skills/:id' });
});

export default Router;

这个模板:

# app/templates/skill.hbs
{{#link-to 'skills.index'}}Back{{/link-to}}
{{model.name}}
{{model.description}}

{{#each user in model.user}}
  {{user.nickname}}
{{/each}}

我只想要一个包含昵称的用户列表。这是我api的回复:

{
  "skills": {
    "id": 1,
    "name": "Ember",
    "description": "JS Framework",
    "link": "emberjs.com"
  },
  "users": [
    {
      "id": 1,
      "email": null,
      "nickname": null,
      "bio": null,
      "created_at": "2015-06-21T10:40:34.555Z",
      "updated_at": "2015-06-21T10:40:34.555Z"
    },
    {
      "id": 2,
      "email": "test",
      "nickname": "dougui",
      "bio": "blabla",
      "created_at": "2015-06-21T10:40:50.493Z",
      "updated_at": "2015-06-21T10:40:50.493Z"
    },
    {
      "id": 3,
      "email": null,
      "nickname": null,
      "bio": null,
      "created_at": "2015-06-21T20:51:29.546Z",
      "updated_at": "2015-06-21T20:51:29.546Z"
    },
    {
      "id": 4,
      "email": null,
      "nickname": null,
      "bio": null,
      "created_at": "2015-06-21T20:55:11.163Z",
      "updated_at": "2015-06-21T20:55:11.163Z"
    },
    {
      "id": 5,
      "email": null,
      "nickname": null,
      "bio": null,
      "created_at": "2015-06-21T20:55:51.231Z",
      "updated_at": "2015-06-21T20:55:51.231Z"
    },
    {
      "id": 6,
      "email": "email",
      "nickname": "nickname",
      "bio": null,
      "created_at": "2015-06-22T00:01:47.089Z",
      "updated_at": "2015-06-22T00:01:47.089Z"
    }
  ]
}

有关于技能和用户的所有信息,但没有显示任何内容。

为什么我的列表没有呈现?

谢谢!

编辑1

现在,我的api正在发送此{"skill":{"id":2,"name":"Rails","description":"test","user_ids":[2]}}

我有这个型号:

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  link: DS.attr('string'),
  users: DS.hasMany('users', { async: true })
});

我也尝试过:

users: DS.hasMany('users', { async: true })

我不知道该怎么办。是否可以使用当前版本的示例?

1 个答案:

答案 0 :(得分:1)

Ember数据希望你给它一个名为skill而不是skills的对象(skills可以请求多种技能,而不是一个实例。)

接下来:您的模型需要users对象中的skill数组。现在你要单独发送它。

最后一个......你已经放置了完整的users对象,而不仅仅是这些对象的id。在这种情况下,您必须将标记{embedded: 'always'}添加到users属性(阅读更多here