0

In Ember.js if you have a model that has a one-to-many relationship is it possible to generate links based on a property of the parent model?

For example, I have a model and some data like this:

var SuggestionGroup = Ember.Model.extend({
   id: Ember.attr('number'),
   name: Ember.attr('string'),
   suggestions: Ember.hasMany('App.Suggestion', {
      key: 'suggestions',
      embedded: true
   })
});

SuggestionGroup.adapter = Ember.FixtureAdapter.create();

SuggestionGroup.FIXTURES = [
{
    id: 1,
    name: 'Start',
    suggestions: [
        {
            id: 1,
            title: 'Fetching coffee and cake for the Interface Developers',
            description: 'Because they\'re so brilliant',
            upVotes: 10,
            downVotes: 2
        },
        {
            id: 2,
            title: 'Criticising the app devs more',
            description: 'They enjoy a bit of banter',
            upVotes: 8,
            downVotes: 4
        },
        {
            id: 3,
            title: 'Not updating JIRA',
            description: 'It\'ll be funny when the PMs start raging',
            upVotes: 1000000,
            downVotes: 0
        }
    ]
}]

And here are my routes:

App.Router.map(function() {
   this.resource('current-suggestions');
   this.resource('suggestion', {
      path: '/current-suggestions/:suggestion_id'
   });
});

My template is like this:

{{#each model}}
<td>
    <ul>
    {{#each suggestions}}
        <li class="suggestion">
            <h3>
                {{#linkTo 'suggestion' this}}{{title}}{{/linkTo}}
            </h3>
        </li>
    {{/each}}
    </ul>
</td>
{{/each}}

So, at the moment my paths are current-suggestions/1. But what I'd like to do is have paths such as current-suggestions/Start/1. So, the path is generated using a property from the parent model.

Is it possible to do something like this?

4

1 回答 1

1

@GJK 的最后一条评论已经指出了正确的方向,但让我对你的问题提出一个稍微详细的答案。

您可以这样做的一种方法是挂钩您的serialize功能SuggestionRoute并提供您的最终网址应该具有的缺失动态段,从概念上讲,这将是这样的:

在您的情况下,将额外的动态段添加到您的路线定义中:name

App.Router.map(function() {
  this.resource('current-suggestions');
  this.resource('suggestion', {
    path: '/current-suggestions/:name/:suggestion_id'
 });
});

然后像这样为动态段提供数据:

App.SuggestionRoute = Ember.Route.extend({
  ...
  serialize: function(model) {
    var id = model.get('id');
    var name = model.get('name');
    return {
        name: name, suggestion_id: id
    }
  }
});

注意:此解决方案假设您为模型提供name父模型的属性Suggestion,要实现这一点,您可以重新考虑模型关系。

并启发您如何重构您的应用程序以实现您的目标(具有 url 之类的/current-suggestions/Start/1等)请看这里:

演示

我试图模拟您的用例,但采用不同的方法。

我希望它有所帮助。

于 2013-07-18T22:15:23.437 回答