Reputation: 850
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?
Upvotes: 0
Views: 223
Reputation: 23322
The last comment from @GJK was pointing already in the right direction, but let me propose a somewhat elaborate answer to your question.
One way you could do it is to hook into the serialize
function of your SuggestionRoute
and provide the missing dynamic segment your final url should have, conceptually this would be like this:
Add the extra dynamic segment to your route definition, in your case :name
App.Router.map(function() {
this.resource('current-suggestions');
this.resource('suggestion', {
path: '/current-suggestions/:name/:suggestion_id'
});
});
And then provide the data for the dynamic segment like this:
App.SuggestionRoute = Ember.Route.extend({
...
serialize: function(model) {
var id = model.get('id');
var name = model.get('name');
return {
name: name, suggestion_id: id
}
}
});
Note: this solution assumes you provide the name
property from your parent model for the Suggestion
model, to achieve this you could rethink your model relationship's.
And to inspire you on how you could refactor your app to achieve your goal (having url's like /current-suggestions/Start/1
etc.) have a look here:
I've tried to simulate your use case but with a different approach.
I hope it helps.
Upvotes: 1