0

我正在构建我的第一个 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'}

关系路由.js.coffee:

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

recipients_route.js.coffee:

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

控制器

关系控制器.js.coffee:

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

关系控制器.js.coffee:

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

楷模

关系.js.coffee:

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

收件人.js.coffee:

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

模板

关系.车把:

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

*更新***

序列化器

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

所有其他代码保持不变

4

1 回答 1

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 尚未加载到关系模型上的属性。

于 2014-02-28T20:22:15.913 回答