10

给定以下 Ember.js 应用程序(使用 Ember 1.0.0.rc.6.1 和 Ember Data 0.13):

App = Ember.Application.create({ LOG_TRANSITIONS: true });

App.Store = DS.Store.extend();

App.Router.map(function() {
    this.resource('promotions', function() {
        this.resource('promotion', { path: '/:promotion_id' }, function() {
            this.resource('entrants', function() {
                this.resource('entrant', { path: '/:entrant_id' });
            });
        });
    });
});

App.PromotionRoute = Ember.Route.extend({
    model: function() {
        return { id: 1, name: 'My Promotion' };
    }
});

App.EntrantsIndexRoute = Ember.Route.extend({
    model: function(params) {
        console.warn('EntrantsIndexRoute', '\nparams:', params, '\nparams.promotion_id:', params.promotion_id, '\narguments:', arguments);
        console.log('params should be:', { promotion_id: 1 });
        console.log('The queried URL should be:', '/entrants?promotion_id=1');
        return App.Entrant.find({promotion_id: params.promotion_id});
    }
});

App.Entrant = DS.Model.extend({
    name: DS.attr('string')
});

如果输入#/promotions/1/entrants应该是嵌套资源的 url ,则 params 是一个空对象。我怎样才能访问promotion_id那里?JSFiddle在这里,点击“点击我”后看一下控制台:http: //jsfiddle.net/Kerrick/4GufZ/

4

2 回答 2

20

虽然您无法访问父路由的动态段,但您仍然可以检索父路由的模型并获取其 ID,如下所示:

App.EntrantsIndexRoute = Ember.Route.extend({
  model: function() {
    var promotion_id = this.modelFor('promotion').id;
    return App.Entrant.find({ promotion_id: promotion_id });
  }
});

或者,如果晋升和参赛者之间存在多方关系,您甚至可以这样做:

App.EntrantsIndexRoute = Ember.Route.extend({
  model: function() {
    return this.modelFor('promotion').get('entrants');
  }
});
于 2013-08-05T19:48:39.477 回答
0

试试这个代码:

App.EntrantsIndexRoute = Ember.Route.extend({
    model: function() {
    var promotion_id = this.modelFor('promotion').query.promotion_id;
    return App.Entrant.find({ promotion_id: promotion_id });
   }
});
于 2013-09-10T03:13:45.673 回答