在Route中获取父对象的ID

时间:2015-05-14 04:39:12

标签: ember.js routes ember-data

我有一个用ember-cli 0.2.3创建的Ember 1.11应用程序。我在router.js文件中有以下内容:

this.route('ownedGames', function() {
    this.route('gamePlays', {path: ":owned_game_id/plays"}, function() { });
});

这允许我使用以下URL:

http://localhost:4200/ownedGames/1/plays

当我访问该网址时,我收到以下错误:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed '<ember-bgg@model:owned-game::ember470:1>' (wrapped in (generated ownedGames.gamePlays controller))

这是我的GamePlay路线

import Ember from 'ember';

export default Ember.Route.extend({
    model: function(params) {
        console.log("Getting game plays from store");
        return this.store.find('gamePlay', {ownedGame: params.owned_game_id});
    }
});

这就是我对夹具数据建模的方式:

OwnedGame.reopenClass({
    FIXTURES: [
        { id: "1", rating: "8.25", game: "1", plays: [1,2]},
        { id: "2", rating: "8.25", game: "2", plays: []},
        { id: "3", rating: "8.25", game: "3", plays: []},
        { id: "4", rating: "8.25", game: "4", plays: []}
    ]
});

GamePlay.reopenClass({
    FIXTURES: [
        {id: "1", date: "2015-01-01", ownedGame: "1"},
        {id: "2", date: "2015-02-01", ownedGame: "1"}
    ]
});

2 个答案:

答案 0 :(得分:0)

在您的路由器地图中,您将:owned_game_dd设置为ownedGames.ownedGame路径中可用,因此该参数不会像您想象的那样在ownedGames.ownedGame.gamePlays路由中可用。为了从另一条路线获取参数,您必须从transition对象获取它们作为model方法的第二个参数。

App.Router.map(function () {
  this.resource('ownedGames', function() {
     this.route('ownedGame', {path: '/:owned_game_id'}, function() {
       this.route('gamePlays', {path: '/plays'}, function() { });
   });
  });
});

App.OwnedGamesOwnedGameGamePlaysRoute = Ember.Route.extend({
    model: function (params, transition) {
         var id = transition.params['ownedGames.ownedGame'].owned_game_id;

         return this.store.find('gamePlay', id);
    }
});

<强> http://emberjs.jsbin.com/favucawadi/1/edit?html,js,output

答案 1 :(得分:0)

如果您的ownGame路线正在设置其模型,您可以通过modelFor()获取模型参考并摘下其ID。这将使您远离父路线的实际参数名称。

Ember在过渡实例上没有关于私有和公共内容的文档,但是它们传递了params并且转换到模型钩子的事实告诉我,从过渡对象中获取params并不是100%安全的除非你可以在未来几个月内进行非弃用通知变更,这很酷。

此外,this.resource()在1.13中已弃用;如果这是一个新项目,我会一直选择this.route()。