处理两个有很多关系

时间:2014-03-08 19:23:33

标签: ember.js

拥有和拥有两个hasMany关系的对象的最佳方式是什么。

型号:

App.Gradebook = DS.Model.extend({
  title: DS.attr('string'),
  students: DS.hasMany('student', { async: true }),
  assignments: DS.hasMany('assignment', { async: true })
});
App.Student = DS.Model.extend({
  name: DS.attr('string'),
  gradebook: DS.belongsTo('gradebook'),
  grades: DS.hasMany('grade', { async: true })
});
App.Assignment = DS.Model.extend({
  title: DS.attr('string'),
  total: DS.attr('number'),
  gradebook: DS.belongsTo('gradebook'),
  grades: DS.hasMany('grade', { async: true })
});
App.Grade = DS.Model.extend({
  score: DS.attr('number'),
  student: DS.belongsTo('student'),
  assignment: DS.belongsTo('assignment')
});

目前,这是我设置它的方式:

模板:

<script type="text/x-handlebars" data-template-name="gradebooks">
  <ul class="nav nav-tabs">
    {{#each}}
      <li {{bind-attr class="isActive:active"}}>
        {{#link-to "gradebook" this}}
          {{title}}
        {{/link-to}}
      </li>
    {{/each}}
  </ul>
  <div class="content">
    {{#if hasGradebooks}}
      {{outlet}}
    {{/if}}
  </div>
</script>

<script type="text/x-handlebars" data-template-name="gradebook">
  <h2>{{title}}</h2>
  <table>
    <thead><tr>
      <th>Students</th>
      {{#each assignments}}
        <th>{{title}} ({{total}})</th>
      {{/each}}
    </tr><thead>
    <tbody>
      {{#each student in students}}
        <tr>
          <td>{{student.name}}</td>
          {{#each assignment in assignments}}
            <td>{{student}}{{assignment}}{{getGrade student assignment}}</td>
          {{/each}}
        </tr>
      {{/each}}
    </tbody>
  </table>
</script>

控制器:

App.GradebookController = Ember.ObjectController.extend({
  getGrade: function(student, assignment) {
    console.log(arguments);
  }
});

现在,除了调用getGrade之外,一切都运行正常。参数输出显示studentassignment作为文字字符串"student""assignment"传递。 {{student}}{{assignment}}的常规输出用于调试并输出类似<App.Student:ember459:1><App.Assignment:ember453:1>的内容,因此我知道它们是对象。

如何从Student电话中获取AssignmentgetGrade个对象?

1 个答案:

答案 0 :(得分:0)

说实话,我甚至不确定你是如何得到getGrade方法的。我不认为这是有效的Hanldebars语法。为了做你想做的事,你将不得不写一个Handlebars助手,详见Ember.js指南here