Multiple models to link-to, last model id used for both routes


#1

So basically the code looks like this:

{{#link-to 'address.comment' address comment}}
  {{title}}
{{/link-to}}

And the relevant routes:

this.resource('address', { path: 'address/:id' }, function () {
  this.route('comment', { path: 'comments/:id' });
});

Now both have an id property, and without over-riding the serialize method for both routes, I get the following url:

addresses/7/comments/7

When address.id is 588 and comment.id is 7. Now If I over-ride the comment serialize route, and not return anything, I get this:

addresses/588/comments/588

No scenario works out correctly, but the funny thing is that when I over-ride both serialize methods, the results for both are correct when stepping through during link building time… Any ideas?


#2

So after talking to @alexspeller on IRC, I now realize that I’ve been using :id, when I should be using :address_id and :comment_id. The model and serialize hooks both expect that format. Hope this helps someone in the future.

Thanks Alex!


#3

But what if the two models are of the same type? As from and to for example. Or in my case parent and child in a hierarchical relation.

I think there is no other option than to adjust one route to have a custom serialize and parameter name?


#4

Assuming you’re having the same problem that @knownasilya was having I think you’d just use :parent_id and :child_id or :from_id and :to_id. The problem above was just that the dynamic segment params were the same (:id) so they would ‘overwrite’ each other if the router was trying to use both at the same time.


#5

Ah, yes. Thank you. I didn’t realize that the _id was the only important part. I thought the mapping was based on the typename.


#6

Both parts are important AFAIK, the first is the model and the second the attribute on the model. So if you want automatic model hook lookup, it makes a difference and you cannot use the same model&attribute twice in a nested route with that method. Personally I try to avoid that auto-lookup, and use camelCased param identifiers, e.g. /users/:userId which gives you the benefit of staying consistent in code:

model({ userId }) {
  return this.store.findRecord('user', userId);
}

The reason I avoid the auto-lookup, is because usually, I end up adding something to the lookup anyway, so I’d have to overwrite it anyway.