如何在Ember.js中获取嵌套模型的记录数

时间:2014-02-28 20:06:08

标签: ember.js ruby-on-rails-4 coffeescript ember-rails

我正在构建我的第一个rails / ember应用程序,使用教程和ember文档中的各种来源进行研究。然而,我已经撞墙了,经过大量的挖掘,我仍然无法找到我正在寻找的答案。目前,我正在构建一个GiftList Rails / Ember应用程序,其中索引页面是关系,并且关系有许多收件人。现在,我有关系显示,我希望它显示每个关系的收件人数,但实际上每个关系显示0,至少有一个关系有一个收件人(家庭有一个记录)。当我检查Ember检查器中的数据时,GiftList.Recipient有1条记录,而GiftList.Relationship有4条记录。如何正确显示正确数量的收件人记录?

路线

Router.js.coffee:

GiftList.Router.map ->
  @resource 'relationships', { path: '/' }, ->
    @resource 'relationship', { path: ':relationship_id' }, ->
      @resource 'recipients', { path: 'recipients' }, ->
        @resource 'recipient', { path: ':recipient_id'}

relationships_route.js.coffee:

GiftList.RelationshipsRoute = Ember.Route.extend
  model: ->
    @store.find('relationship')

recipients_route.js.coffee:

GiftList.RecipientsRoute = Ember.Route.extend
  model: ->
    @store.find('recipient')

控制器

relationships_controller.js.coffee:

GiftList.RelationshipsController = Ember.ArrayController.extend({})

relationship_controller.js.coffee:

GiftList.RelationshipController = Ember.ArrayController.extend
  recipients: GiftList.Recipient.find()

模型

relationship.js.coffee:

GiftList.Relationship = DS.Model.extend
  name: DS.attr('string')
  recipients: DS.hasMany('recipient')

recipient.js.coffee:

GiftList.Recipient = DS.Model.extend
  first_name: DS.attr('string')
  last_name: DS.attr('string')
  relationship: DS.belongsTo('relationship')

模板

relationships.handlebars:

<h2>Relationships</h2>
  <ul id="relationships">
    {{#each}}
      <li>{{name}}({{recipients.length}})</li>
    {{/each}}
  </ul>

* UPDATE ***

串行

class RecipientSerializer < ActiveModel::Serializer
  embed :id
  attributes :id, :first_name, :last_name
  has_one :relationship, key: :relationship

end

class RelationshipSerializer < ActiveModel::Serializer
  embed :ids, include: true
  attributes :id, :name
  has_many :recipients, key: :recipients

end

所有其他代码保持不变

1 个答案:

答案 0 :(得分:0)

我假设您正在使用ember-data beta版本。如果您使用的是旧版本,则此答案将不适用。

当您要获取的内容是特定关系的收件人时,您将获取所有关系和所有收件人。如果您不希望将父模型中的hasMany关系嵌入为侧载记录,则需要声明异步关系:

GiftList.Relationship = DS.Model.extend
  name: DS.attr('string')
  recipients: DS.hasMany('recipient', { async: true })

然后你只需要获得关系的收件人:

GiftList.RecipientsRoute = Ember.Route.extend
  model: ->
    @modelFor('relationship').get('recipients')

这将对/ relationships /:id / recipients进行异步调用以获取关系的收件人,因为您要求在关系模型上尚未加载异步的hasMany属性。