Route未正确提供模型(已过滤的数组)

时间:2015-06-02 14:13:28

标签: ember.js ember-data

我对Ember和JS框架一般都很陌生,我正在构建我的第一个玩具应用程序。我遇到了一个我必须实施的特定问题。 我的玩具应用程序包含以下路线和模型:

Router.map(function() {
  this.resource('books', {path: '/'});
  this.resource('book', {path: '/books/:book_id'});
  this.resource('genre', {path: '/genres/:genre_id'});
});

export default DS.Model.extend({
  title: DS.attr('string'),
  author: DS.attr('string'),
  genre: DS.belongsTo('genre', {async: true}),
  review: DS.attr('string'),
  rating: DS.attr('number'),
  amazon_id: DS.attr(),
  url: function() {
    return "http://www.amazon.com/gp/product/"+this.get('amazon_id')+"/adamfortuna-20";
  }.property('amazon_id'),
  image: function() {
    return "http://images.amazon.com/images/P/"+this.get('amazon_id')+".01.ZTZZZZZZ.jpg";
  }.property('amazon_id')
})

export default DS.Model.extend({
  name: DS.attr('string'),
  books: DS.hasMany('book', {async: true})
})

我希望路径/ genres /:genre_id为我生成一个模型,该模型是包含特定类型的每本书的数组:

export default Ember.Route.extend({
  model: function(params) {
    return this.store.filter('book', function(book) {
      return book.get('genre') === params.genre_id
    });
  }
});

这是我的genre.hbs模板:

<h2> Books </h2>
<ul class="list-unstyled">
  {{#each}}
    {{book-details book=this tag='li' class='row'}}
  {{/each}}
</ul>

没有渲染,控制台返回:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed '<DS.FilteredRecordArray:ember466>' (wrapped in (generated genre controller))

任何帮助都会非常感激。感谢

1 个答案:

答案 0 :(得分:0)

我假设你在流派路线中也需要genre模型。最好将模型设置为流派(这样您可以使用{{link-to 'genre' genre}}transitionTo('genre', genre)),并在afterModel钩子中设置书籍。

// genre route
export default Ember.Route.extend({

  model: function(params) {
    return this.store.find('genre', params.genre_id);
  },

  afterModel: function(model) {
     var self = this;
    // model here is genre already resolved
    // to find books we just need to resolve model.get('books') promise
    return model.get('books').then(function(books){
       self.controllerFor('genre').set('books', books);
       // genre.books stored in controller as books
    });
  }
});

// genre template
<h2> Books of {{model.name}} genre ({{books.length}})</h2>
<ul class="list-unstyled">
  {{#each books as |book|}}
    {{book-details book=book tag='li' class='row'}}
  {{/each}}
</ul>