如何在Ember中显示HasMany关系

时间:2014-01-17 03:30:58

标签: ember.js

使这个简单的jsfiddle显示包含产品的类别列表需要做什么,例如

  • 蔬菜
    • 胡萝卜
    • 芦笋

查看代码:

<script type="text/x-handlebars" data-template-name="categories">
    {{#each}}
        <div>Category: {{name}}</div>
            {{#each product in this.products}}
                <div>Product: {{product.name}}</div>            
            {{/each}}
    {{/each}}
</script>

型号代码:

App.Category = DS.Model.extend({
    name: DS.attr('string'),
    products: DS.hasMany('product')
});

App.Product = DS.Model.extend({
    name: DS.attr('string')
});

路线:

App.CategoriesRoute = Ember.Route.extend({
    model: function () {
        return this.store.find('category');
    }
});

3 个答案:

答案 0 :(得分:1)

您需要使关系异步并修复json(删除id)

异步,因为记录未包含在类别

没有附加ID,因为这不是Ember Data期望https://github.com/emberjs/data/blob/master/TRANSITION.md

的格式
App.Category = DS.Model.extend({
    name: DS.attr('string'),
    products: DS.hasMany('product', {async: true})
});

App.Category.FIXTURES = [
    {    id: 1,    name: 'Shirts',   products: [1]},
    {    id: 2,    name: 'Pants',    products: [1,2]},
    {    id: 3,    name: 'Socks',    products: [3]},
    {    id: 4,    name: 'Shoes',    products: [3,4]}
];

http://jsfiddle.net/2Mguy/

答案 1 :(得分:1)

这是一个功能齐全的jsfiddle,演示了如何执行此操作。

其他一个答案指出,您需要将{ async: true }添加到hasMany关系,并从Ids移除products

但是,它确实没有修复所有渲染问题。您还需要将默认路由更改为:

App.Router.map(function () {
    this.route('categories', { path: "/" });
});

然后,创建一个CategoriesController扩展Ember.ArrayControlleritemController设置为'category'。 (有关详细信息,请参阅Ember文档)然后,您可以创建CategoryController扩展Ember.ObjectController

最后,将您的#each语句更新为:

{{#each category in controller}}

同样,这里是JSfiddle演示如何运作。

答案 2 :(得分:-1)

简单"How To"Ruby on Rails 4

-app /串行化器/ list_serializer.rb

class ListSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name
  has_many :tasks
end

-app /串行化器/ task_serializer.rb

class TaskSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :list_id
end

-app / Javascript角/模型/ task.js

EmTasks.Task = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr("string"),
  list: DS.belongsTo('list')
});

-app / Javascript角/模型/ list.js

EmTasks.List = DS.Model.extend({
  name: DS.attr('string'),
  tasks: DS.hasMany('task')
});

样本列表控制器:

class ListsController < ApplicationController
  respond_to :json

  def index
    respond_with List.all
  end
# ...

然后,您将获得标准REST JSON API(JSON)的/lists.json响应:

{
  lists: [
    {
      id: 15,
      name: "icebox",
      task_ids: [
        1
      ]
    }
  ],
  tasks: [
    {
      id: 1,
      name: "whatever",
      description: "",
      list_id: 15
    }
  ]
}

您可以在handlebars模板中打印:

  {{#each task in this.tasks}}
    {{task.name}}
  {{/each }}